Home  >  Article  >  Web Front-end  >  Examples of how JavaScript sorts arrays and objects

Examples of how JavaScript sorts arrays and objects

黄舟
黄舟Original
2017-07-18 10:04:511499browse

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);

Console output result:


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

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);

Descending output:


##

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

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


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

Output result:


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

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

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}
];

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);
 });
}

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!

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