JavaScript Development Space

Sort Map by Value in JavaScript

Sorting a Map by its values in JavaScript can be a useful technique for organizing data more effectively. This guide will walk you through the process of sorting a Map by its values using straightforward code examples. Whether you’re working with numerical data or custom objects, you’ll learn how to leverage JavaScript’s features to achieve sorted results efficiently.

js
1 const searchTerms = new Map();
2 searchTerms.set(3, 'javascript');
3 searchTerms.set(1, 'python');
4 searchTerms.set(12, 'c++');
5 searchTerms.set(5, 'kotlin');
6 searchTerms.set(4, 'rust');
7
8 Array.from(searchTerms.entries())
9 .sort((a, b) => a[0] - b[0])
10 .map(([number, term]) => {
11 console.log('number-term', number, term);
12 });
13
14 // Output:
15 //
16 // number-term 1 python
17 // number-term 3 javascript
18 // number-term 4 rust
19 // number-term 5 kotlin
20 // number-term 12 c++
JavaScript Development Space

Follow JavaScript Development Space

Stay updated with the latest trends, tutorials, and best practices in JavaScript development. Follow our JavaScript Development blog for expert insights, coding tips, and resources to enhance your web development skills.

© 2024 JavaScript Development Blog. All rights reserved.