const myMap = new Map();
myMap.set("a",3);
myMap.set("c",4);
myMap.set("b",1);
myMap.set("d",2);
// sort by value
const mapSort1 = new Map([...myMap.entries()].sort((a, b) => b[1] - a[1]));
console.log(mapSort1);
// Map(4) {"c" => 4, "a" => 3, "d" => 2, "b" => 1}
const mapSort2 = new Map([...myMap.entries()].sort((a, b) => a[1] - b[1]));
console.log(mapSort2);
// Map(4) {"b" => 1, "d" => 2, "a" => 3, "c" => 4}
// sort by key
const mapSort3 = new Map([...myMap.entries()].sort());
console.log(mapSort3);
// Map(4) {"a" => 3, "b" => 1, "c" => 4, "d" => 2}
const mapSort4 = new Map([...myMap.entries()].reverse());
console.log(mapSort4);
// Map(4) {"d" => 2, "b" => 1, "c" => 4, "a" => 3}
Yo could take a different approach and change Symbol.iterator
of Map.prototype[@@iterator]()
for a custom sorted result.
var map = new Map();
map.set("orange", 10);
map.set("apple", 5);
map.set("banana", 20);
map.set("cherry", 13);
map[Symbol.iterator] = function* () {
yield* [...this.entries()].sort((a, b) => a[1] - b[1]);
}
for (let [key, value] of map) { // get data sorted
console.log(key + ' ' + value);
}
console.log([...map]); // sorted order
console.log([...map.entries()]); // original insertation order
.as-console-wrapper { max-height: 100% !important; top: 0; }
In ES6 you can do it like this: (assume your Map object is m
).
[...m].map(e =>{ return e[1];}).slice().sort(function(a, b) {
return a - b;
});
the spread operator turns a Map object into an array, then takes out the second element of each subarray to build a new array, then sort it. If you want to sort in descending order just replace a - b
with b - a
.
You can shorten the function and use this in ES6- using arrow function (lambda)
let m2= new Map([...m.entries()].sort((a,b) => b[1] - a[1]))
You can use list maps instead of map only. Try this:
var yourListMaps = [];
var a = {quantity: 10, otherAttr: 'tmp1'};
var b = {quantity: 20, otherAttr: 'tmp2'};
var c = {quantity: 30, otherAttr: 'tmp3'};
yourListMaps.push(a);
yourListMaps.push(b);
yourListMaps.push(c);
And if you want to sort by quantity, you can:
// Sort c > b > a
yourListMaps.sort(function(a,b){
return b.quantity - a.quantity;
});
or
// Sort a > b > c
yourListMaps.sort(function(a,b){
return a.quantity - b.quantity;
});
To sort a map object use the below code.
const map = new Map();
map.set("key","value");
map.set("key","value");
const object = Object.keys(map.sort().reduce((a,b) => (a[k] = map[a], b), {});
console.log(object);
//This will work to sort a map by key.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With