Search code examples
typescriptsortinglodash

Need to sort an array of objects with two string elements (countries) on the country name typescript or lodash


I have an array of objects like this:

{
     countries: [{
        "country_alpha2_code": "PW",
        "country_name": "PALAU"
        },{
        "country_alpha2_code": "US",
        "country_name": "UNITED STATES"
        }
     ]
}

What I need done is to sort on country_name only, the two character code is not necessary, to give this:

{
     countries: [
        {
        "country_alpha2_code": "US",
        "country_name": "UNITED STATES"
        },{
        "country_alpha2_code": "PW",
        "country_name": "PALAU"
        }
     ]
}

I used lodash to make the new array of objects. This will go into a dropdown.

I tried this first:

// this.newJSONCountryArr.sort((a,b) => priorityIndex[a.country_name - b.country_alpha2_code]);

Nothing. Then this:

this.newJSONCountryArr.sort(this.compare);
console.log('New Country Arr: ', self.newJSONCountryArr);

compare(a: { country_name: string; }, b: { country_name: string; }): number{
  if (a.country_name < b.country_name) {
    return -1;
  }
  if (a.country_name > b.country_name) {
    return 1;
  }
  return 0;
}

I really don't need a number returned I simply want to sort the array of objects based on the objects I have by country_name.


Solution

  • const countriesFromDb = [
      {
        country_alpha2_code: 'US',
        country_name: 'UNITED STATES'
      },
      {
        country_alpha2_code: 'PW',
        country_name: 'PALAU'
      }
    ];
    
    const sorted = [...countriesFromDb].sort((a, b) =>
      a.country_name.localeCompare(b.country_name)
    );