Home >Web Front-end >JS Tutorial >How Can I Sort JavaScript Object Properties by Their Values?

How Can I Sort JavaScript Object Properties by Their Values?

Susan Sarandon
Susan SarandonOriginal
2024-12-25 16:09:24404browse

How Can I Sort JavaScript Object Properties by Their Values?

Sorting Object Properties by Values

Sorting an object's properties based on their values in JavaScript can be achieved through an ingenious workaround. Rather than relying on the implementation-dependent ordering of object properties, we can convert them into an array, sort the array, and recreate the object.

To accomplish this, we move the object properties into an array using a loop:

let sortable = [];
for (var vehicle in maxSpeed) {
    sortable.push([vehicle, maxSpeed[vehicle]]);
}

Once in array form, we can utilize the sort function to sort the elements by value:

sortable.sort(function(a, b) {
    return a[1] - b[1];
});

This yields an array in sorted order:

// [["bike", 60], ["motorbike", 200], ["car", 300],
// ["helicopter", 400], ["airplane", 1000], ["rocket", 28800]]

From the sorted array, we can reconstruct the object while preserving the desired order:

let objSorted = {}
sortable.forEach(function(item){
    objSorted[item[0]]=item[1]
})

Alternatively, if ES8 is available, we can utilize the Object.entries and reduce methods to transform the object into an array:

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

This approach remains a workaround due to implementation quirks, and one should avoid relying on the order of object properties in JavaScript.

The above is the detailed content of How Can I Sort JavaScript Object Properties by Their Values?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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