How to sort a map in JavaScript ?
In JavaScript, a map can be sorted in multiple ways. Here are some methods to sort a map in JavaScript:
Method 1: Using the Array.sort() method
1. Convert the map to an array of key-value pairs using the Map.entries()
method.
2. Sort the array using the Array.sort()
method and a custom sorting function that compares the values of the key-value pairs.
3. Convert the sorted array back to a map using the Map()
constructor.
Example:
let myMap = new Map();
myMap.set("John", 25);
myMap.set("Mary", 30);
myMap.set("Bob", 20);
let sortedMap = new Map([...myMap.entries()].sort((a, b) => a[1] - b[1]));
console.log(sortedMap); // Output: Map { 'Bob' => 20, 'John' => 25, 'Mary' => 30 }
Method 2: Using the lodash library
1. Install the lodash library using npm or yarn.
2. Import the sortBy()
function from the lodash library.
3. Pass the map and a custom function that returns the value of each key-value pair to the sortBy()
function.
Example:
const _ = require('lodash');
let myMap = new Map();
myMap.set("John", 25);
myMap.set("Mary", 30);
myMap.set("Bob", 20);
let sortedMap = new Map(_.sortBy(Array.from(myMap), [(o) => o[1]]));
console.log(sortedMap); // Output: Map { 'Bob' => 20, 'John' => 25, 'Mary' => 30 }
Method 3: Using the Map() constructor and the spread operator
1. Convert the map to an array of key-value pairs using the Map.entries()
method.
2. Sort the array using the Array.sort()
method and a custom sorting function that compares the values of the key-value pairs.
3. Create a new map using the Map()
constructor and the spread operator to add the sorted key-value pairs to the new map.
Example:
let myMap = new Map();
myMap.set("John", 25);
myMap.set("Mary", 30);
myMap.set("Bob", 20);
let sortedArray = [...myMap].sort((a, b) => a[1] - b[1]);
let sortedMap = new Map(sortedArray);
console.log(sortedMap); // Output: Map { 'Bob' => 20, 'John' => 25, 'Mary' => 30 }