Get the App
SLTechnology News&Howtos  ›  Development  › 

How js sorts an array of objects

Shulou Source: shulou.com Published: 2022-06-01 03:22:14 09月20日 Update

This article is about how js sorts an array of objects. The editor thinks it is very practical, so share it with you as a reference and follow the editor to have a look.

Sort an array of objects

JavaScript arrays often contain objects:

Example

Var cars = [{type: "Volvo", year:2016}, {type: "Saab", year:2001}, {type: "BMW", year:2010}]

The sort () method can be used to sort an array even if the object has properties of different data types.

The solution is to compare attribute values by comparing functions:

Example

Cars.sort (function (a, b) {return a.year-b.year})

Comparing string properties is a little more complicated:

Example

Cars.sort (function (a, b) {var x = a.type.toLowerCase (); var y = b.type.toLowerCase (); if (x)

< y) {return -1;} if (x >

Y) {return 1;} return 0;}); Thank you for reading! This is the end of the article on "how to sort the array of objects in js". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, you can share it for more people to see!

Tags: Objects arrays sorting instances properties contents methods more articles different good complex practical functions characters strings frequent meetings data articles see Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Xiaomi Shulou Technology OPPO Reno Huawei Linux