Sort an Associative Array by Its Keys in JavaScript | Plantpot

Sort an Associative Array by Its Keys in JavaScript

Web Dev
Sponsored links

In this article, I will introduce how to sort an associative array by its keys in JavaScript.

Sort an associative array by its keys

There are several ways to sort by the key of an associative array, that is, the property name, but this time we will introduce the following method.

  1. Get the property name list of the object with the Object.keys() function
  2. Sort the list with the sort() function
  3. Use the sorted property name list to retrieve the property values ​​in order

Sample Code

Below is sample code to sort by the method introduced above.

const stock = {
  orange: 5,
  banana: 3,
  apple: 10,
  grape: 7
};

for(key in stock) {
  console.log(`${key} : ${stock[key]}`);
}
// orange: 5
// banana: 3
// apple: 10
// grape: 7


// Sort
keys = Object.keys(stock);
keys.sort();
for(key of keys) {
  console.log(`${key} : ${stock[key]}`);
}
// apple : 10
// banana : 3
// grape : 7
// orange : 5