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 };
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]]
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]; });
This gives us the sorted object:
objSorted = { "bar": 15, "me": 75, "you": 100, "foo": 116 };
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);
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!