The following discussion is related to the array object sorting code example tutorial article for sorting arrays and object arrays through js. The content is a carefully selected and organized tutorial. I hope it will be helpful to everyone. The following is the detailed content:
Code example tutorial for sorting arrays and object arrays through js
Note: the sort() method will change the original array, and the default is to sort the array in unicode order
Recommended js related video tutorials: https://www.php.cn/course/list/17/type/2.html
1. js The sort method implements array sorting
var arr = [2,3,13,17,4,19,1]; arr.sort() // [1, 13, 17, 19, 2, 3, 4]
If you want to sort the array according to size, you need to add a comparison function to the sort() method of js
var arr = [2,3,13,17,4,19,1]; arr.sort(function(a,b){ // 比较函数 return b - a; // 降序, 升序为 a - b }) console.log(arr) // [19, 17, 13, 4, 3, 2, 1]
2. js The sort method implements the sorting of object arrays
is similar to the usage in arrays
var arr = [ { name:"小明", age:12 }, { name:"小红", age:11 }, { name:"小刚", age:15 }, { name:"小华", age:13 } ]; function compare(p){ //比较函数 return function(m,n){ var a = m[p]; var b = n[p]; return a - b; } } arr.sort(compare("age")); console.log(arr); //升序,结果: [{name: "小红", age: 11}, {name: "小明", age: 12}, {name: "小华", age: 13},
I would like to point out any shortcomings, thank you very much!
For more js-related questions, please visit the PHP Chinese website, which has a wealth of js tutorials.
Website: https://www.php.cn/
The above is the detailed content of Code detailed example operations for sorting arrays and object arrays in JS. For more information, please follow other related articles on the PHP Chinese website!