Search code examples
javascriptjavascript-objects

Sorting an object based on property integer values in descending order


So, i have object of cities with scores attached to them, like so :
let cityScores = { Milan: 1, Malta: 3, Palma: 5, Ibiza: 2, Porto: 1 };
What i want to do is to get an array, with the highest-scoring city as its first item (in this case, Palma), and following cities by descending scores.

I thought long and hard about this, and came up with this solution. I just wanted to ask, isn't there anything better out there? A useful method or some other way out that i might be missing? This is how i do it :

First of all, i find max value in the object. Then, i check for every city and i make sure that the one with highest value is/are in the beginning of array. Then i tried using .push() to push the lowest-scoring cities to the end, but i just couldn't. I can't push "city" properly while i'm still looping over these cities, because cities are randomly. The best approach i found was to "remember" cities by their score and store them in these arrays (secondaryCities, tertiaryCities, etc) and then push them one by one.

let cityScores = { Milan: 1, Malta: 3, Palma: 5, Ibiza: 2, Porto: 1 };
let cityScoreKeys = Object.keys(cityScores);
let cityScoreValues = Object.values(cityScores);
let maxScore = Math.max(...cityScoreValues);
let arrangedCities = [];
let secondaryCities = [];
let tertiaryCities = [];
let quaternaryCities = [];
for (i = 0; i < cityScoreKeys.length; i++) {
  if (cityScores[cityScoreKeys[i]] == maxScore) {
    arrangedCities.unshift(cityScoreKeys[i]);
  } else if (cityScores[cityScoreKeys[i]] === maxScore - 1) {
    secondaryCities.push(cityScoreKeys[i]);
  } else if (cityScores[cityScoreKeys[i]] === maxScore - 2) {
    tertiaryCities.push(cityScoreKeys[i]);
  } else if (cityScores[cityScoreKeys[i]] === maxScore - 3) {
    quaternaryCities.push(cityScoreKeys[i]);
  }
}
let nonMaxCities = [secondaryCities, tertiaryCities, quaternaryCities];
for (i = 0; i < nonMaxCities.length; i++) {
  arrangedCities.push(...nonMaxCities[i]);
}

Solution

  • Here's my solution:

    let cityScores = { Milan: 1, Malta: 3, Palma: 5, Ibiza: 2, Porto: 1 };
    
    let obj = Object.keys(cityScores).map(function(key) {
      return {key, value: cityScores[key]};
    });
    
    let result = obj.sort((a,b) => b.value - a.value);
    
    console.log(result);