Categories
JavaScript Answers

How to sort an associative array by its values in JavaScript?

Spread the love

Sometimes, we want to sort an associative array by its values in JavaScript.

In this article, we’ll look at how to sort an associative array by its values in JavaScript.

How to sort an associative array by its values in JavaScript?

To sort an associative array by its values in JavaScript, we use some object methods.

For instance, we write

const sortedObj = Object.fromEntries(
  Object.entries(data).sort(([, val1], [, val2]) => val1 - val2)
);

to call Object.entries with data to return an array with the key-value pairs in their own arrays.

Then we call sort with a callback that gets the property values from each array and compare them to do the sorting and return the sorted array.

Then we call Object.fromEntries to convert the array of key-value pair arrays back into an object.

Conclusion

To sort an associative array by its values in JavaScript, we use some object methods.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *