How Javascript Sort Map? Explain in 3 Methods

JavaScript is a versatile programming language that allows developers to work with different data structures, including maps. So, in this article, we will explore multiple methods to sort a map in JavaScript, providing step-by-step guidance and code examples to help you master the process.

Sorting a map can be a crucial task in various scenarios, ensuring data is organized and easily accessible. Before jumping into the different sorting methods let’s grasp the fundamental concepts of maps in JavaScript.

What is Map?

A map, also known as an associative array or dictionary, is a collection of elements where each element is stored as a key-value pair.

The keys are unique and used to access the corresponding values. In JavaScript, you can create a map using the Map() constructor, and it allows any data type to be used as keys.

For example:

// Creating a map in JavaScript
const myMap = new Map();
myMap.set("JAVASCRIPT", 3);
myMap.set("JAVA", 5);
myMap.set("PHP", 2);

This given example program demonstrates the creation of a map with three key-value pairs, representing the quantities of programming lanaguages.
The keys are strings (“JAVASCRIPT”, “JAVA”, and “PHP”), and the values are numbers (3, 5, and 2).

What is JavaScript sort map?

In Javascript, a sorting map is a collection of key-value pairs, wherein keys are unique and sorted based on the values.
Unlike regular objects, a Sort Map guarantees the order of its elements, making it ideal for scenarios that require data organization.

Now, let’s explore various methods to sort this map efficiently.

How to sort map in javascript

Map in Javascript is an object that stores key-value pairs. Primarily, the order of items in a map is insertion order.

However, if we want to sort the map based on certain criteria, you can use the following methods and techniques:

Method 1: Use Array to Sort the Map

One of the methods we can utilize is to convert the map into an array of key-value pairs, then sort array based on the key-value pairs and create a new map from the sorted array.

See the example program below:

const originalMap = new Map([
  ['Javascript', 3],
  ['PHP', 2],
  ['JAVA', 1],
]);

// Convert map to array of key-value pairs
const sortedArrayByKey = Array.from(originalMap);

// Sort array based on keys
sortedArrayByKey.sort((a, b) => a[0].localeCompare(b[0]));

// Create a new map from the sorted array
const sortedMapByKey = new Map(sortedArrayByKey);

console.log(sortedMapByKey);

Output:

{JAVA: 1, Javascript: 3, PHP: 2}

Apart from it, we can sort based on the values:

const originalMap = new Map([
  ['Javascript', 3],
  ['PHP', 2],
  ['JAVA', 1],
]);

// Convert map to array of key-value pairs
const sortedArrayByValue = Array.from(originalMap);

// Sort array based on values
sortedArrayByValue.sort((a, b) => a[1] - b[1]);

// Create a new map from the sorted array
const sortedMapByValue = new Map(sortedArrayByValue);

console.log(sortedMapByValue);

Output:

{JAVA: 1, Javascript: 3, PHP: 2}

Method 2: Sorting map in Place

Another approach is sorting pa in place, in this case, we can sort the original map directly without creating a new one.
Obviously, we can’t directly sort the map in place however we can clear the original map and then set sorted key value pairs back into it.

Study the example program below:

const originalMap = new Map([
  ['JavaScript', 3],
  ['PHP', 2],
  ['JAVA', 1],
]);

const sortedArrayByKey = Array.from(originalMap);
sortedArrayByKey.sort((a, b) => a[0].localeCompare(b[0]));

// Clear the original map
originalMap.clear();

// Set the sorted key-value pairs back into the map
sortedArrayByKey.forEach(([key, value]) => originalMap.set(key, value));

console.log(originalMap);

Result:

{JAVA: 1, JavaScript: 3, PHP: 2}

It is important to note that JavaScript maps are ordered by insertion, so the keys will be sorted in ascending order when using localeCompare.

For numerical values, you can use the comparison function a[1] – b[1].

Note: The insertion order behavior of maps is relatively new, so if you need to support older browsers, consider using an array or another data structure for sorting instead.

Method 3: Sort Map using Loadash library

Also, we can utilize Lodash to sort map, it is a popular JavaScript utility library that provides a convenient sortBy() function to sort objects based on specific properties.
To use Lodash for sorting maps, make sure to include the library in your project.

// Import the Lodash library
const _ = require('lodash');

// Your original map
const myMap = new Map([
  ['JAVASCRIPT', 3],
  ['JAVA', 1],
  ['PHP', 2],
  ['PYTHON', 4]
]);

// Sorting the map by keys using Lodash
const sortedMapByKeys = new Map(_.sortBy([...myMap.entries()]));

// Sorting the map by values using Lodash
const sortedMapByValues = new Map(_.sortBy([...myMap.entries()], ([key, value]) => value));

// Display the sorted maps
console.log('Sorted Map by Keys:');
for (const [key, value] of sortedMapByKeys) {
  console.log(key, value);
}

console.log('Sorted Map by Values:');
for (const [key, value] of sortedMapByValues) {
  console.log(key, value);
}

FAQs

How to sort a map in JavaScript?

One way to sort the key-value pairs in a specific order, you should use an array of objects instead of a plain object.

Can I sort a map with complex object keys?

Yes, JavaScript maps allow any data type to be used as keys, including complex objects. You can sort maps with objects as keys using the methods mentioned in this article.

Will sorting a map modify the original map?

No, sorting a map will not modify the original map. Instead, it will create a new sorted map or array, leaving the original map unchanged.

Additional Resources

Conclusion

In conclusion, sorting a map in JavaScript is a valuable skill for any developer working with complex data structures.

In this article, we explored various methods to sort a map efficiently, ranging from simple conversion to arrays and using built-in array methods to leveraging the power of the Lodash library.

Understanding the fundamentals and using the appropriate sorting technique for your specific use case will result in well-organized and optimized code.

Frequently Asked Questions

Is JavaScript still worth learning in 2026?
Yes. JavaScript runs on 98% of websites for the front-end, dominates the back-end via Node.js, powers mobile apps through React Native, builds desktop tools through Electron, and is the scripting layer for most AI tooling (LangChain.js, OpenAI SDK, Vercel AI). Whether you target web, mobile, AI, or full-stack capstones, JavaScript is the broadest single language you can learn.
What is the difference between var, let, and const?
var is function-scoped, hoisted to the top of its scope, and can be redeclared, which leads to bugs in modern code. let is block-scoped (only visible inside the nearest {}) and can be reassigned. const is block-scoped and cannot be reassigned, although object contents can still mutate. Default to const for everything, switch to let only when you actually need to reassign, and avoid var in any code written after 2017.
Which JavaScript version should I target in 2026?
Target ES2020 (ES11) as the safe baseline because every modern browser and Node.js 14+ supports it fully. ES2022 adds useful features like top-level await, private class fields with the # prefix, and the .at() array method. If you are writing for older browsers (IE11 or older Android WebViews), transpile down with Babel or use a build tool like Vite, esbuild, or webpack.
What is the best free editor for JavaScript?
Visual Studio Code is the industry standard, free, with built-in IntelliSense, debugger, terminal, Git, and a huge extension marketplace (ESLint, Prettier, GitHub Copilot, Tailwind). Install the JavaScript and TypeScript Nightly extension for the latest language features. JetBrains WebStorm is more powerful and free for students with a verified .edu email. For quick scratchpad work, the Chrome DevTools Sources panel includes a workspace and breakpoint debugger.
How do I run JavaScript locally vs in the browser?
In the browser: open DevTools with F12 (or right-click then Inspect), go to the Console tab, type or paste your code, press Enter. For HTML pages, add a script tag pointing to your .js file. Locally with Node.js: download Node from nodejs.org (LTS version), then run node script.js in your terminal from the file folder. Use the same Node setup for backend capstones, API integrations, and scripts that do not need a browser.
What can I build with JavaScript for my BSIT capstone?
Common BSIT capstones in JavaScript: full-stack web apps using React or Vue on the front-end with Node.js and Express on the back-end (MongoDB or MySQL for the database), real-time chat or notification systems using Socket.io, single-page dashboards with Chart.js or D3.js, cross-platform mobile apps with React Native, AI-powered chatbots using OpenAI SDK and LangChain.js, and Chrome extensions for productivity tools. Add Tailwind CSS for the UI and Vercel or Netlify for free deployment.

Glay Eliver


Programmer & Technical Writer at PIES IT Solution

Glay Eliver is a programmer and writer at PIES IT Solution, author of over 600 tutorials at itsourcecode.com. Specializes in JavaScript tutorials, Microsoft Office how-tos (Excel, Word, PowerPoint), and Python error debugging covering ImportError, TypeError, AttributeError, ModuleNotFoundError, and JavaScript ReferenceError. Authored several of the site’s highest-traffic Excel and MS Office reference articles.

Expertise: JavaScript · MS Excel · MS Word · MS PowerPoint · Python · Python ImportError · Python TypeError · Python AttributeError · ModuleNotFoundError · JavaScript ReferenceError · Pygame
 · View all posts by Glay Eliver →

Leave a Comment