0

How can sort the values 1,99,1,50 in javascript?

Here is input: var map = {test:1, test2:99, test3:1, test4: 50}

here is the targeted output: {test2:99, test4:50, test3:1, test:1}

Here is what I have tried:

function sortMap(map) {
    var temp = [];
    for(let prop in map) {
        if(map.hasOwnProperty(prop)) {
            temp.push({name:prop, size:map[prop]});
        }
    }
    return temp.sort(function(b, a) {
        return a.size - b.size
    });
}
Luca Putzu
  • 1,438
  • 18
  • 24
РАВИ
  • 11,467
  • 6
  • 31
  • 40

1 Answers1

0

You cannot actually sort an object's keys, but you can sort the keys and get the values accordingly.

var map = { test: 1, test2: 99, test3: 1, test4: 50 },
    keys = Object.keys(map).sort(function (a, b) { return map[b] - map[a]; });

keys.forEach(function (k) {
    document.write(k + ': ' + map[k] + '<br>');
});
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392