1

I have the map posted below in the code section. what i want to achieve is, to sort the map according to the values ascendingly. so that, after sorting it, i should the map sorted as shown in last section.

please let me know how can i achieve that.

code:

const map = {};
map['test.truck'] = 10;
map['test.domain'] = -20;
map['test.institute'] = 0;
map['test.vehicle'] = 40;
map['test.lan'] = 1;
map['test.wifi'] = 9;

after sorting:

map['test.domain'] = -20;
map['test.institute'] = 0;
map['test.lan'] = 1;
map['test.wifi'] = 9;
map['test.truck'] = 10;
map['test.vehicle'] = 40;
Amrmsmb
  • 1
  • 27
  • 104
  • 226

5 Answers5

2

You can do:

const map = {};
map['test.truck'] = 10;
map['test.domain'] = -20;
map['test.institute'] = 0;
map['test.vehicle'] = 40;
map['test.lan'] = 1;
map['test.wifi'] = 9;

const mapSorted = Object
  .keys(map)
  .sort((a, b) => map[a] - map[b])
  .reduce((a, c) => (a[c] = map[c], a), {});

console.log(mapSorted);
Yosvel Quintero
  • 18,669
  • 5
  • 37
  • 46
  • thanks. now, if i have a map contains {object, Number},can I use the code you posted to sort it? or the code is only applicable if the key is a string? please advise – Amrmsmb Mar 29 '18 at 16:08
0

First, an important distinction: what you're using is an object, not a map. JavaScript has a separate Map class.

In any case, what you're asking for is not possible. Map entries do not have an internal order; it is entirely up to the JavaScript implementation to decide what order it returns them in when you iterate over them.

Máté Safranka
  • 4,081
  • 1
  • 10
  • 22
0

What you trying to do is sort object by property values.

Example:

const list = {"you": 100, "me": 75, "foo": 116, "bar": 15};
const listSorted = Object.keys(list)
       .sort((a, b) => list[a]-list[b])
       .reduce((obj, key) => ({
         ...obj, 
         [key]: list[key]
       }), {})
semanser
  • 2,310
  • 2
  • 15
  • 33
0

You should use these library.

https://www.npmjs.com/package/treemap-js

Jimmy Pannier
  • 261
  • 1
  • 2
  • 16
0

You'd have to convert to an array first and sort then:

function sortProperties(obj)
{
  // convert object into array
    var sortable=[];
    for(var key in obj)
        if(obj.hasOwnProperty(key))
            sortable.push([key, obj[key]]); // each item is an array in format [key, value]

    // sort items by value
    sortable.sort(function(a, b)
    {
        var x=a[1].toLowerCase(),
            y=b[1].toLowerCase();
        return x<y ? -1 : x>y ? 1 : 0;
    });
    return sortable; // array in format [ [ key1, val1 ], [ key2, val2 ], ... ]
}
bojax
  • 41
  • 8