Help to sort an array

¡Hello! I have this object, with a some arrays inside, and i’m trying to sort it by the amount of money they produce in a year ( Gross domestic product ) [GDP] and at the same time updates the property called rank from highest to lowest GDP.

const countryData = [
  { rank: 5, name: "Norway", gpd: 77975.4 },
  { rank: 3, name: "Macao", gpd: 81151.9 },
  { rank: 4, name: "Ireland", gpd: 77771.2 },
  { rank: 2, name: "Luxembourg", gpd: 113196.5 },
  { rank: 6, name: "Qatar", gpd: 69687.7 },
  { rank: 1, name: "Switzerland", gpd: 83716.8 },
];

Output should look like this:

const countryData = [
  { rank: 1, name: "Luxembourg", gpd: 113196.5 },
  { rank: 2, name: "Switzerland", gpd: 83716.8 },
  { rank: 3, name: "Macao", gpd: 81151.9 },
  { rank: 4, name: "Norway", gpd: 77975.4 },
  { rank: 5, name: "Ireland", gpd: 77771.2 },
  { rank: 6, name: "Qatar", gpd: 69687.7 },
];

I been trying with sort() method, like this:

const orderer = countryData.sort((a,b) => 
  a.gpd < b.gpd ? 1 : -1);
  console.log(orderer);  

And works! but i have no clue of how update rank property.

Thanks in advance!

You can iterate over the array (with a for loop or a .map) and set rank to the index +1 after the sort.

I’m trying! thanks for the advice!

Good luck and happy coding!

I’m done! i can’t do that.

what do you mean?

if you still need help, post your code and explain what issue you are having

1 Like

This is what i got so far. I have no idea about how to reset rank and print in in order of the const orderer. I know i have to use .map() method.

Output shuld look like this:

const countryData = [
  { rank: 1, name: "Luxembourg", gpd: 113196.5 },
  { rank: 2, name: "Switzerland", gpd: 83716.8 },
  { rank: 3, name: "Macao", gpd: 81151.9 },
  { rank: 4, name: "Norway", gpd: 77975.4 },
  { rank: 5, name: "Ireland", gpd: 77771.2 },
  { rank: 6, name: "Qatar", gpd: 69687.7 },
];

and what have you tried there?

You don’t have to use .map(). If you’re not comfortable with .map() you can just use a normal for loop. What have you tried so far?

const orderer = countryData.sort((a,b) => a.gpd < b.gpd ? 1 : -1)
                           .map((countryRank, Countrylength) => countryRank.rank * 0 + Countrylength + 1)
  console.log(orderer);

It’s returning just an array [1,2,3,4,5,6] but not rest of items.

That’s because your map function is only returning the number.

So i have to push that array of numbers to country.rank. Or just return the whole array updated in the same map method?

Thanks for your advices!

whatever data type you want in the final array, the map method callback needs to return - do you need an array of objects? the callback needs to return an object

2 Likes