当前位置:网站首页>[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;
}
}
边栏推荐
- C # draw Bezier curve with control points for lattice images and vector graphics
- 一篇文章带你走进cookie,session,Token的世界
- OpenGL - Lighting
- Unity skframework framework (24), avatar controller third person control
- 微信小程序获取住户地区信息
- Analysis of eventbus source code
- Applet data attribute method
- 太不好用了,长文章加图文,今后只写小短文
- Unity SKFramework框架(二十四)、Avatar Controller 第三人称控制
- 顶会论文看图对比学习(GNN+CL)研究趋势
猜你喜欢
Using request headers to develop multi terminal applications
Hosting environment API
OpenGL - Coordinate Systems
c语言指针深入理解
一篇文章带你走进cookie,session,Token的世界
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
Svg optimization by svgo
Principle and performance analysis of lepton lossless compression
[ctfhub] Title cookie:hello guest only admin can get flag. (cookie spoofing, authentication, forgery)
Newton iterative method (solving nonlinear equations)
随机推荐
NIPS2021 | 超越GraphCL,GNN+对比学习的节点分类新SOTA
【el-table如何禁用】
Understanding of smt32h7 series DMA and DMAMUX
一题多解,ASP.NET Core应用启动初始化的N种方案[上篇]
Applet (subcontracting)
OpenGL - Lighting
Composition of applet code
Kotlin introductory notes (III) kotlin program logic control (if, when)
Applet customization component
微信小程序获取住户地区信息
云计算技术热点
MySQL does not take effect in sorting string types
[ManageEngine] how to make good use of the report function of OpManager
【对象数组的排序】
Kotlin introductory notes (VI) interface and function visibility modifiers
Transfer learning and domain adaptation
OpenGL - Model Loading
Ministry of transport and Ministry of Education: widely carry out water traffic safety publicity and drowning prevention safety reminders
2309. The best English letters with both upper and lower case
C语言-从键盘输入数组二维数组a,将a中3×5矩阵中第3列的元素左移到第0列,第3列以后的每列元素行依次左移,原来左边的各列依次绕到右边