How to Sort a Map in JavaScript?
Last Updated :
17 Sep, 2024
Sorting a Map in JavaScript involves ordering its key-value pairs based on the keys or values. Since Maps maintain the insertion order, you can't directly sort them like arrays. Instead, you'll need to convert the Map into an array, sort it, and then convert it back into a Map.
Below are the approaches to sorting a map in JavaScript:
Approach 1: Using Map.entries() and sort() Method
The Map.entries() and sort() method approach involves converting a Map's entries into an array, sorting the array by keys or values with sort(), and then converting the sorted array back into a new Map.
Syntax:
[...map1.entries()]
# this will generate a multi-dimensional array
# out of the key-value pairs stored in the map
Example 1: In this example we initializes a Map, adds elements using set(), sorts the Map's entries by keys with sort(), and then prints only the keys of the sorted Map.
JavaScript
// Initializing and inserting values into Map
let map1 = new Map([
[4, 2],
[2, 3],
]);
// Inserting new element into map using set() method
map1.set(3, 10);
console.log("Our map :");
console.log(map1);
// Adding the sorting logic
map1 = new Map([...map1.entries()].sort());
// Separately printing only keys
for (let [key, value] of map1) {
console.log(key, " ");
}
OutputOur map :
Map(3) { 4 => 2, 2 => 3, 3 => 10 }
2
3
4
Approach 2: Using Array.from() and sort() Method
The Array.from() and sort() approach involves converting a Map to an array using Array.from(), then sorting the array with the sort() method based on keys or values. Finally, the sorted array is converted back into a new Map.
Example: In this example,, we are using Array.from() and sort() Method
JavaScript
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);
OutputMap(3) { 4 => 2, 2 => 3, 3 => 10 }
Map(3) { 4 => 2, 2 => 3, 3 => 10 }
Approach 3: Using Lodash's _.sortBy function
The Lodash _.sortBy function approach sorts a Map by converting it into an array using Array.from(), applying _.sortBy for custom sorting by keys or values, and converting the sorted array back into a Map for further use.
Example: In this example we initializes a Map, adds a new element, and sorts it by values in ascending order using Lodash's _.sortBy function. The sorted Map is then printed, showing the reordered entries.
JavaScript
// 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 to the map
console.log("Original map:");
console.log(map1);
// Sorting the map by increasing values of keys using lodash
const sortedMap = new Map(_.sortBy(Array.from(map1), [(entry) => entry[1]]));
console.log("Sorted map:");
console.log(sortedMap);
Output:
Sorted map: Map { 'orange' => 2, 'banana' => 3, 'apple' => 5, 'grape' => 10 }
Similar Reads
How to serialize a Map in JavaScript ? In this article, we will discuss, the serialization of maps in JavaScript. Serialization is the conversion of an object or a data structure to another format that is easily transferrable on the network. In JavaScript, the format suitable for transferring is JSON string. So, we usually call the JSON.
2 min read
How to iterate over Map elements in JavaScript ? Map() is very useful in JavaScript it organises elements into key-value pairs. This method iterates over each element in an array and applies a callback function to it, allowing for modifications before returning the updated array." The Map() keyword is used to generate the object. The map() method
3 min read
How are elements ordered in a Map in JavaScript ? In JavaScript, a new object called Map was introduced in the ES6 version. A map is a collection of elements where each element is stored in a key, value pair. Map objects can store both objects as well as primitive data types. The elements of a map are iterable. Elements are always iterated in the i
2 min read
What is JavaScript Map and how to use it ? What is Map?A Map in JavaScript is a collection of key-value pairs where keys can be any data type. Unlike objects, keys in a Map maintain insertion order. It provides methods to set, get, delete, and iterate over elements efficiently, making it useful for data storage and retrieval tasks.Syntaxnew
2 min read
How to Sort a Map in JavaScript? Sorting a Map in JavaScript involves ordering its key-value pairs based on the keys or values. Since Maps maintain the insertion order, you can't directly sort them like arrays. Instead, you'll need to convert the Map into an array, sort it, and then convert it back into a Map.Below are the approach
3 min read
How to map array values without using map method in JavaScript ? Array elements can be mapped by using looping methods in JavaScript. The map() method creates a new array with the results of the output of a function called for each array element. This can also be implemented using a for loop in JavaScript.Approach 1: For this, we can create two arrays, in which o
3 min read
What is the difference between Map and WeakMap in JavaScript ? In this article, we will talk about the difference between Map and WeakMap which are introduced by ES6. Javascript object supports only one key object. For supporting multiple key objects, Then Map comes on this path. Map: A Map is an unordered list of key-value pairs where the key and the value can
4 min read
How To Convert Map Keys to an Array in JavaScript? Here are the various methods to convert Map keys to an array in JavaScript1. Using array.from() MethodThe Array.from() method in JavaScript converts Map keys to an array by using 'Array.from(map.keys())'. JavaScriptlet map = new Map().set('GFG', 1).set('Geeks', 2); let a = Array.from(map.keys()); co
2 min read
How to convert a plain object into ES6 Map using JavaScript ? The task is to convert a JavaScript Object into a plain ES6 Map using JavaScript. we're going to discuss a few techniques. To understand the difference between a map and an object please go through the Map vs Object in JavaScript article. Below are the following approaches to converting a plain obje
2 min read
JavaScript - Use map() on an Array in Reverse Order Here are the different methods to use map() on an array in reverse order with JavaScript1. Using JavaScript array.reverse() methodThe idea is to use the .reverse() method just after applying the .slice() method. Then use the .map() method on the reversed array to perform the task.JavaScriptlet a = [
3 min read