0

I have the following objects being returned from my api

country {Code: "AT", Country: "Austria", Nationality: "Austrian"}
country {Code: "BE", Country: "Belgium", Nationality: "Belgian"}
country {Code: "CH", Country: "Switzerland", Nationality: "Swiss"}
country {Code: "DE", Country: "Germany", Nationality: "German"}
country {Code: "ES", Country: "Spain", Nationality: "Spanish"}

I need to return these in the order of the 'Country' not 'Code'.

Here is my code

this.countries = _.map(list, (item) => {
    const code = item.iso;
    const country = _.find(countries, (country) => country.Code == code);

    //const maryPoppins = _.sortBy(country, ['country.Country']);
    //console.log('maryPoppins',maryPoppins)

    //returns the above objects
    console.log('country', country)

    return {
        code: code,
        name: country
    }
});

I tried both sortBy and orderBy (lodash) but I think I need to merge each object into a new array and then return / sort the result.

Any help greatly appreciated

1 Answers1

0

You can use localeCompare to sort strings

let arr = [{Code: "AT", Country: "Austria", Nationality: "Austrian"}
 ,{Code: "BE", Country: "Belgium", Nationality: "Belgian"}
 ,{Code: "CH", Country: "Switzerland", Nationality: "Swiss"}
 ,{Code: "DE", Country: "Germany", Nationality: "German"}
 ,{Code: "ES", Country: "Spain", Nationality: "Spanish"}
 ,{Code: "IT", Country: "Italy", Nationality: "Italian"}
 ,{Code: "NL", Country: "Netherlands", Nationality: "Dutch"}
 ,{Code: "PL", Country: "Poland", Nationality: "Polish"}]

arr.sort((a,b) => a.Country.localeCompare(b.Country))

console.log(arr)
Nitish Narang
  • 4,124
  • 2
  • 15
  • 22