How to useArray.from() and sort() Method in Javascript
In this method, we will use Array.from() which is used to convert the map into an array, and then by using the sort() function we will sort the map. In this method, we will sort the map by values.
Example: In this example,, we are using Array.from() and sort() Method
let map1 = new Map([
[4, 2],
[2, 3],
]);
// Inserting new element into map using set() method
map1.set(3, 10);
console.log(map1);
// Adding the custom sorting logic to sort
// by decreasing values of keys
const newMap = Array.from(map1).sort((a, b) => a[1] - b[1]);
const sortedMap = new Map(newMap);
console.log(sortedMap);
Output
Map(3) { 4 => 2, 2 => 3, 3 => 10 } Map(3) { 4 => 2, 2 => 3, 3 => 10 }
How to sort a map in JavaScript ?
We will see how to sort the Map according to the value of the keys.
Map in JavaScript is a special kind of object that stores elements in terms of [key, value] pair. The map can store both primitive as well as objects. When iterating over the map object, it returns the [key, value] pair in the same order as inserted.
Below are the following approaches:
Table of Content
- Using Map.entries() and sort() Method
- Using Array.from() and sort() Method