The content of this article is about how to use the sort() method in js? The sort method in js implements the sorting of arrays and object arrays (code attached). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
The sort() method will change the original array, which is arranged in unicode order by default
1. The sort method in js 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 For sorting, you need to add a comparison function in 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. The sort method of js 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}, {name: "小刚", age: 15}]
Related recommendations:
js simulates the sort method of Array_javascript skills
Usage of sort() method in Js_Basic knowledge
Example of using sort method of array in JS_javascript skills
The above is the detailed content of What are the uses of sort() method in js? The sort method in js implements sorting of arrays and object arrays (code attached). For more information, please follow other related articles on the PHP Chinese website!