Home > Web Front-end > JS Tutorial > Javascript object array is sorted according to the value of the object key_javascript skills

Javascript object array is sorted according to the value of the object key_javascript skills

WBOY
Release: 2016-05-16 16:10:51
Original
1713 people have browsed it

There is a js object array var ary=[{id:1,name:"b"},{id:2,name:"b"}]. The requirement is to sort based on the value of name or id. Here is Coquettish function

Function definition:

Copy code The code is as follows:

function keysrt(key,desc) {
return function(a,b){
Return desc ? ~~(a[key] < b[key]) : ~~(a[key] > b[key]);
}
}

Use:

Copy code The code is as follows:

var ary=[{id:1,name:"b"},{id:2,name:"b"}];
ary.sort(keysrt('name',true));
ary.sort(keysrt('name',false));
ary.sort(keysrt('id',false));

The above is the entire content of this article. If you are in need, please come and study it carefully, haha.

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