当前位置:网站首页>[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;
}
}
边栏推荐
- LeetCode 503. 下一个更大元素 II
- 【饿了么动态表格】
- 2311. Longest binary subsequence less than or equal to K
- Wechat applet obtains household area information
- 【el-table如何禁用】
- 2310. 个位数字为 K 的整数之和
- 云计算技术热点
- Hosting environment API
- Understanding of smt32h7 series DMA and DMAMUX
- [beauty of algebra] solution method of linear equations ax=0
猜你喜欢
Kotlin introductory notes (VII) data class and singleton class
Creation and reference of applet
C form click event did not respond
Unity skframework framework (24), avatar controller third person control
LeetCode 31. Next spread
Newton iterative method (solving nonlinear equations)
Rebuild my 3D world [open source] [serialization-3] [comparison between colmap and openmvg]
A keepalived high availability accident made me learn it again
LeetCode 31. 下一个排列
mysql安装配置以及创建数据库和表
随机推荐
SMT32H7系列DMA和DMAMUX的一点理解
L'information et l'entropie, tout ce que vous voulez savoir est ici.
【组队 PK 赛】本周任务已开启 | 答题挑战,夯实商品详情知识
Huber Loss
MySQL does not take effect in sorting string types
Project practice | excel export function
Alibaba's ten-year test brings you into the world of APP testing
fs. Path module
[team PK competition] the task of this week has been opened | question answering challenge to consolidate the knowledge of commodity details
利用请求头开发多端应用
【对象数组的排序】
Can't find the activitymainbinding class? The pit I stepped on when I just learned databinding
22-07-04 Xi'an Shanghao housing project experience summary (01)
Lepton 无损压缩原理及性能分析
Unity skframework framework (XXIII), minimap small map tool
Svgo v3.9.0+
浅谈Label Smoothing技术
Ministry of transport and Ministry of Education: widely carry out water traffic safety publicity and drowning prevention safety reminders
图神经网络+对比学习,下一步去哪?
nodejs_ 01_ fs. readFile