当前位置:网站首页>【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;
}
}
边栏推荐
- Uni app implements global variables
- Introduction Guide to stereo vision (7): stereo matching
- Talking about the difference between unittest and pytest
- 使用el-upload封装得组件怎么清空已上传附件
- 干货整理!ERP在制造业的发展趋势如何,看这一篇就够了
- Nodejs modularization
- The research trend of map based comparative learning (gnn+cl) in the top paper
- 微信小程序获取住户地区信息
- 我的一生.
- Applet global style configuration window
猜你喜欢

Introduction Guide to stereo vision (7): stereo matching

干货整理!ERP在制造业的发展趋势如何,看这一篇就够了

一篇文章带你走进cookie,session,Token的世界

编辑器-vi、vim的使用

LeetCode 556. Next bigger element III

The research trend of map based comparative learning (gnn+cl) in the top paper

Information and entropy, all you want to know is here

Kotlin introductory notes (II) a brief introduction to kotlin functions

一文详解图对比学习(GNN+CL)的一般流程和最新研究趋势

Unity skframework framework (24), avatar controller third person control
随机推荐
Explain NN in pytorch in simple terms CrossEntropyLoss
什么是防火墙?防火墙基础知识讲解
【组队 PK 赛】本周任务已开启 | 答题挑战,夯实商品详情知识
Kotlin introductory notes (IV) circular statements (simple explanation of while, for)
Thermometer based on STM32 single chip microcomputer (with face detection)
Figure neural network + comparative learning, where to go next?
Generate confrontation network
MySQL does not take effect in sorting string types
一次 Keepalived 高可用的事故,让我重学了一遍它
干货整理!ERP在制造业的发展趋势如何,看这一篇就够了
Applet global style configuration window
Talking about label smoothing technology
OpenGL - Model Loading
Hosting environment API
[beauty of algebra] solution method of linear equations ax=0
Kotlin introductory notes (II) a brief introduction to kotlin functions
Kotlin introductory notes (VII) data class and singleton class
fs. Path module
.NET服务治理之限流中间件-FireflySoft.RateLimit
混淆矩阵(Confusion Matrix)