Sunday, December 10, 2017

null values can throw off TypeScript/JavaScript sorting

This can have some funny results if some of what is being sorted has no value. Solve that problem like so:

let presidentsCopy:Array<President> = JSON.parse(JSON.stringify(this.presidents));
presidentsCopy = presidentsCopy.sort((yin, yang) => {
   let yinParty:string = "";
   let yangParty:string = "";
   if (yin.Party){
      yinParty = yin.Party;
   }
   if (yang.Party){
      yangParty = yang.Party;
   }
   if (yinParty > yangParty){
      return 1;
   }
   if (yinParty < yangParty){
      return -1;
   }
   return 0;
});

No comments:

Post a Comment