0

I am trying to sort a map using below function

var m=new Map();
    m.set('0900','0910');
    m.set('1100','1200');
    m.set('1000','1030');
    m.set('1235','1240');
    var ma=new Map([...m.entries()].sort());
    console.log(ma);

Output:{ 900 => 910, 1000 => 1030, 1100 => 1200, 1235 => 1240}

the map is getting sorted, but when I use the integers instead of characters I can't able to sort it

 var m=new Map();
    m.set(0900,0910);
    m.set(1100,1200);
    m.set(1000,1030);
    m.set(1235,1240);
    var ma=new Map([...m.entries()].sort());
    console.log(ma)

Output: {1000 => 1030, 1100 => 1200, 1235 => 1240, 900 => 910}

chsaiteja
  • 3
  • 1

3 Answers3

2

sort() function, when you don't supply a compareFunction as an argument, does not really work the way you instinctively expect it to work. See the following quote from relevant MDN page:

If compareFunction is not supplied, all non-undefined array elements are sorted by converting them to strings and comparing strings in UTF-16 code units order. For example, "banana" comes before "cherry". In a numeric sort, 9 comes before 80, but because numbers are converted to strings, "80" comes before "9" in the Unicode order. All undefined elements are sorted to the end of the array.

The numeric sort bit in the quote explains why you're getting two different sorts with strings and numbers (with "0900" and 900). To overcome this, simply provide a function to the sort to the comparisons the way you want it, like so:

let ma = new Map([...m.entries()].sort((a, z) => a[0] - z[0]);

You can look into the details of how these compareFunctions work in the same MDN page: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort

selmanbey
  • 318
  • 1
  • 8
0

Here, extract the first element with the help of destructuring out of the array and compare it.

 var m=new Map();
    m.set(0900,0910);
    m.set(1100,1200);
    m.set(1000,1030);
    m.set(1235,1240);
    var ma=new Map([...m.entries()].sort(([a], [b]) => a - b));

for(const e of ma) {
   console.log(e);
}
bill.gates
  • 14,145
  • 3
  • 19
  • 47
-1

MDN on Map.entries():

The entries() method returns a new Iterator object that contains the [key, value] pairs for each element in the Map object in insertion order.

When calling .sort() on the entries, it first converts the key-value pairs into strings before sorting them. That means that 0900 becomes 900, which comes after 1235, because '9' > '1' (first character of each string).

If you want to sort the entries by key, you will need to pass in a custom compareFunction argument to sort, which handles the key-value pairs and compares the keys as numbers:

var m = new Map();
m.set(0900,0910);
m.set(1100,1200);
m.set(1000,1030);
m.set(1235,1240);

var ma = new Map([...m.entries()].sort((kv1, kv2) => kv1[0] - kv2[0]));
console.log(ma);
Billy Brown
  • 2,272
  • 23
  • 25