Friday, May 10, 2024
 Popular · Latest · Hot · Upcoming
98
rated 0 times [  103] [ 5]  / answers: 1 / hits: 138050  / 8 Years ago, thu, june 23, 2016, 12:00:00

How to sort this map by value?


var map = new Map();
map.set('orange', 10);
map.set('apple', 5);
map.set('banana', 20);
map.set('cherry', 13);

More From » sorting

 Answers
20

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; }




[#61677] Monday, June 20, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
mckinley

Total Points: 15
Total Questions: 101
Total Answers: 94

Location: Liechtenstein
Member since Fri, Sep 11, 2020
4 Years ago
;