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.