Examples of how JavaScript sorts arrays and objects

黄舟
Release: 2017-07-18 10:04:51
Original
1443 people have browsed it

This article mainly introduces relevant information on examples of javascript array sorting and object sorting. Friends in need can refer to

javascript examples of array sorting and object sorting

Array sorting

When using JavaScript, we all discovered that the sort function actually sorts in dictionary order, such as the following example:


var ary = [2, 98, 34, 45, 78, 7, 10, 100, 99]; ary.sort(); console.log(ary);
Copy after login

Console output result:


Array [ 10, 100, 2, 34, 45, 7, 78, 98, 99 ]
Copy after login

This also obviously verifies what I wrote before. The above result is the comparison The first element of the array, and then arrange it in this order 1-9, then we need to pass a comparison function to the sort function (I still have to mention the function pointer in C language here, which simply means giving a function Pass in another function, and what you pass in is like you give your own set of rules, and the computer will execute it according to your rules). This is also the case now. If you give a rule, then please Look at the following code:


var ary = [2, 98, 34, 45, 78, 7, 10, 100, 99]; ary.sort((a, b) => { return a-b; }); console.log(ary);
Copy after login

Descending output:


##

ary.sort(function(a, b) { return b-a; }); console.log(ary);
Copy after login

The function passed in is written in ES6. Equivalent to:


ary.sort(function(a, b) { return a-b; });
Copy after login

Output result:


Array [ 2, 7, 10, 34, 45, 78, 98, 99, 100 ] Array [ 100, 99, 98, 78, 45, 34, 10, 7, 2 ]
Copy after login

Object sorting

The sorting object we are going to talk about today is to place multiple objects in an array as follows


var objArray = [ {name : 'lily', age : 22}, {name : 'kandy', age : 20}, {name : 'lindy', age : 24}, {name : 'Jone', age : 27} ];
Copy after login

You need to sort them next:


function sortObj(array, key) { return array.sort(function(a, b) { var x = a[key]; var y = b[key]; return x - y; //或者 return x > y ? 1 : (x < y ? -1 : 0); }); }
Copy after login
Console output:


The above is the detailed content of Examples of how JavaScript sorts arrays and objects. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
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 Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!