Home > Web Front-end > JS Tutorial > How to Sort JavaScript Objects by Property Values?

How to Sort JavaScript Objects by Property Values?

Linda Hamilton
Release: 2024-12-29 09:42:11
Original
799 people have browsed it

How to Sort JavaScript Objects by Property Values?

Sorting Objects by Property Values

In JavaScript, objects are unordered collections of key-value pairs. However, there may be situations where we need to sort objects based on the values of their properties. This can be achieved by converting the object to an array, sorting the array by values, and then reconstructing the object from the sorted array.

Let's consider the example provided:

var list = {
  "you": 100, 
  "me": 75, 
  "foo": 116, 
  "bar": 15
};
Copy after login

To sort the properties of list based on their values, we can do the following:

let sortable = [];
for (let property in list) {
    sortable.push([property, list[property]]);
}

sortable.sort((a, b) => a[1] - b[1]);

// [["bar", 15], ["me", 75], ["you", 100], ["foo", 116]]
Copy after login

This creates an array sortable containing subarrays of property-value pairs, which are then sorted in ascending order based on the values. Now, we can reconstruct the object in the sorted order:

let objSorted = {};
sortable.forEach(item => {
    objSorted[item[0]] = item[1];
});
Copy after login

This gives us the sorted object:

objSorted = {
  "bar": 15, 
  "me": 75, 
  "you": 100, 
  "foo": 116
};
Copy after login

In ES8 and above, we can simplify this process using Object.entries():

const maxSpeed = {
  car: 300, 
  bike: 60, 
  motorbike: 200, 
  airplane: 1000,
  helicopter: 400, 
  rocket: 8 * 60 * 60
};

const sortable = Object.entries(maxSpeed)
  .sort(([,a],[,b]) => a-b)
  .reduce((r, [k, v]) => ({ ...r, [k]: v }), {});

console.log(sortable);
Copy after login

This returns the sorted array of property-value pairs as an object.

It's important to note that while sorting objects by property values is possible, it relies on an implementation quirk in JavaScript and may break in the future. It's recommended to avoid making assumptions about the order of elements in JavaScript objects.

The above is the detailed content of How to Sort JavaScript Objects by Property Values?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template