当前位置:网站首页>[JS sort according to the attributes in the object array]
[JS sort according to the attributes in the object array]
2022-07-05 09:28:00 【Guodong pudding】
【js Sort according to the attributes in the object array 】
var arr = [
{name:'a',age:9},
{name:'b',age:12},
{name:'c',age:8}
];
arr.sort((a,b)=>{
return a.age - b.age
});
function compare(property){
return function(a,b){
var value1 = a[property];
var value2 = b[property];
return value1 - value2;
}
}
console.log(arr.sort(compare('age')))
* Examples of use :newArray.sort(sortBy('number',false)) // Express basis number Attribute descending ; If the second parameter is not passed , Default means ascending sort
* @param attr The properties of sorting Such as number attribute
* @param rev true Indicates ascending order ,false null
* */
sortBy: function(attr,rev){
// The second parameter is not passed Default ascending order
if(rev == undefined){
rev = 1;
}else{
rev = (rev) ? 1 : -1;
}
return function(a,b){
a = a[attr];
b = b[attr];
if(a < b){
return rev * -1;
}
if(a > b){
return rev * 1;
}
return 0;
}
}
边栏推荐
- Wechat applet obtains household area information
- Applet data attribute method
- Alibaba's ten-year test brings you into the world of APP testing
- 干货整理!ERP在制造业的发展趋势如何,看这一篇就够了
- 2309. The best English letters with both upper and lower case
- 【愚公系列】2022年7月 Go教学课程 003-IDE的安装和基本使用
- Project practice | excel export function
- Nips2021 | new SOTA for node classification beyond graphcl, gnn+ comparative learning
- Kotlin introductory notes (VIII) collection and traversal
- 【js 根据对象数组中的属性进行排序】
猜你喜欢
随机推荐
Talking about label smoothing technology
My life
Rebuild my 3D world [open source] [serialization-3] [comparison between colmap and openmvg]
Using request headers to develop multi terminal applications
OpenGL - Model Loading
Greendao reported an error in qigsaw, could not init daoconfig
Cloud computing technology hotspot
C language - input array two-dimensional array a from the keyboard, and put 3 in a × 5. The elements in the third column of the matrix are moved to the left to the 0 column, and the element rows in ea
Node の MongoDB Driver
Unity SKFramework框架(二十二)、Runtime Console 运行时调试工具
Unity skframework framework (24), avatar controller third person control
STM32简易多级菜单(数组查表法)
VS Code问题:长行的长度可通过 “editor.maxTokenizationLineLength“ 进行配置
【PyTorch Bug】RuntimeError: Boolean value of Tensor with more than one value is ambiguous
Lepton 无损压缩原理及性能分析
利用请求头开发多端应用
Deep understanding of C language pointer
Introduction Guide to stereo vision (3): Zhang calibration method of camera calibration [ultra detailed and worthy of collection]
22-07-04 Xi'an Shanghao housing project experience summary (01)
驾驶证体检医院(114---2 挂对应的医院司机体检)