Home > Web Front-end > JS Tutorial > body text

Code detailed example operations for sorting arrays and object arrays in JS

王林
Release: 2019-08-21 11:54:45
Original
2078 people have browsed it

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]
Copy after login

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]
Copy after login

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},
Copy after login

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!

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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template