Sorting a Map
in JavaScript requires converting it into an array, sorting it, and then converting it back into a Map
. Below are the common approaches to sort a Map
based on keys or values.
1. Using Map.entries()
and sort()
Method
- Converts
Map.entries()
into an array - Sorts the array by keys
- Converts it back into a
Map
Example: Sorting by Keys (Ascending)
let map1 = new Map([
[4, 2],
[2, 3]
]);
map1.set(3, 10);
console.log("Original Map:", map1);
// Sorting by keys
map1 = new Map([...map1.entries()].sort());
console.log("Sorted by Keys:");
for (let [key, value] of map1) {
console.log(key, value);
}
Output:
Original Map: Map(3) { 4 => 2, 2 => 3, 3 => 10 }
Sorted by Keys:
2 3
3 10
4 2
2. Using Array.from()
and sort()
Method
- Converts
Map
to an array usingArray.from()
- Sorts it based on keys or values
- Converts it back to a
Map
Example: Sorting by Values (Ascending)
let map1 = new Map([
[4, 2],
[2, 3]
]);
map1.set(3, 10);
console.log("Original Map:", map1);
// Sorting by values in ascending order
const newMap = Array.from(map1).sort((a, b) => a[1] - b[1]);
const sortedMap = new Map(newMap);
console.log("Sorted by Values:", sortedMap);
Output:
Original Map: Map(3) { 4 => 2, 2 => 3, 3 => 10 }
Sorted by Values: Map(3) { 4 => 2, 2 => 3, 3 => 10 }
3. Using Lodash’s _.sortBy
Function
- Converts
Map
to an array - Uses
_.sortBy()
to sort based on values - Converts back into a
Map
Example: Sorting by Values (Ascending)
// Importing the lodash library
const _ = require('lodash');
let map1 = new Map([
['banana', 3],
['apple', 5],
['orange', 2],
]);
map1.set('grape', 10); // Adding a new element
console.log("Original Map:", map1);
// Sorting by values in ascending order
const sortedMap = new Map(_.sortBy(Array.from(map1), [(entry) => entry[1]]));
console.log("Sorted Map:", sortedMap);
Output:
Sorted Map: Map { 'orange' => 2, 'banana' => 3, 'apple' => 5, 'grape' => 10 }
Summary
Method | Sorting Criteria | Convert Back to Map? |
---|---|---|
Map.entries() + sort()
|
Sorts by keys | Yes |
Array.from() + sort()
|
Sorts by keys or values | Yes |
Lodash _.sortBy()
|
Sorts by values | Yes |
Each method is useful depending on whether you need to sort by keys or values. 🚀
Top comments (0)