How js sorts an array of objects
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!