当前位置:网站首页>【js 根据对象数组中的属性进行排序】
【js 根据对象数组中的属性进行排序】
2022-07-05 09:27:00 【果东布丁】
【js 根据对象数组中的属性进行排序】
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')))
* 使用例子:newArray.sort(sortBy('number',false)) //表示根据number属性降序排列;若第二个参数不传递,默认表示升序排序
* @param attr 排序的属性 如number属性
* @param rev true表示升序排列,false降序排序
* */
sortBy: function(attr,rev){
//第二个参数没有传递 默认升序排列
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;
}
}
边栏推荐
- [ctfhub] Title cookie:hello guest only admin can get flag. (cookie spoofing, authentication, forgery)
- MySQL does not take effect in sorting string types
- Huber Loss
- Talking about label smoothing technology
- Wechat applet obtains household area information
- Node collaboration and publishing
- 【阅读笔记】图对比学习 GNN+CL
- Kotlin introductory notes (I) kotlin variables and non variables
- 【ManageEngine】如何利用好OpManager的报表功能
- AUTOSAR from getting started to mastering 100 lectures (103) -dbc file format and creation details
猜你喜欢
Android 隐私沙盒开发者预览版 3: 隐私安全和个性化体验全都要
High performance spark_ Transformation performance
Nodemon installation and use
LeetCode 496. Next larger element I
使用el-upload封装得组件怎么清空已上传附件
Unity SKFramework框架(二十二)、Runtime Console 运行时调试工具
Progressive JPEG pictures and related
OpenGL - Model Loading
Applet (use of NPM package)
[team PK competition] the task of this week has been opened | question answering challenge to consolidate the knowledge of commodity details
随机推荐
[technical school] spatial accuracy of binocular stereo vision system: accurate quantitative analysis
OpenGL - Model Loading
Hosting environment API
Hi Fun Summer, play SQL planner with starrocks!
Multiple solutions to one problem, asp Net core application startup initialization n schemes [Part 1]
深入浅出PyTorch中的nn.CrossEntropyLoss
LeetCode 503. Next bigger Element II
一篇文章带你走进cookie,session,Token的世界
Editor use of VI and VIM
The research trend of map based comparative learning (gnn+cl) in the top paper
Vs code problem: the length of long lines can be configured through "editor.maxtokenizationlinelength"
Jenkins Pipeline 方法(函数)定义及调用
【组队 PK 赛】本周任务已开启 | 答题挑战,夯实商品详情知识
Unity skframework framework (24), avatar controller third person control
迁移学习和域自适应
Wxml template syntax
云计算技术热点
Talking about the difference between unittest and pytest
Jenkins pipeline method (function) definition and call
[team PK competition] the task of this week has been opened | question answering challenge to consolidate the knowledge of commodity details