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
WBOYOriginal
2016-05-16 16:10:511699browse

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.

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