当前位置:网站首页>JS中对象数组用sort按属性排序
JS中对象数组用sort按属性排序
2022-08-03 16:38:00 【m0_49471668】
1.比较数字
var numbers = [4, 2, 5, 1, 3];
numbers.sort((a, b) => a - b);
console.log(numbers);
// [1, 2, 3, 4, 5]2.对象属性排序
其实在我们实际开发中,经常会遇到这样的问题,我们收到后端传过来的数据,然后我们需要根据数据中的某一项来排序。
比如有以下数据:
var items = [
{ name: 'Edward', value: 21 },
{ name: 'Sharpe', value: 37 },
{ name: 'And', value: 45 },
{ name: 'The', value: -12 },
{ name: 'Zeros', value: 37 }
];1.按对象value排序
// sort by value
items.sort((a, b) => Number(a.value) - Number(b.value));
2.按对象name排序
// sort by name
items.sort(function(a, b) {
//忽略大小写
var nameA = a.name.toUpperCase();
var nameB = b.name.toUpperCase();
if (nameA < nameB) {
return -1;
}
if (nameA > nameB) {
return 1;
}
//name相等时
return 0;
});

边栏推荐
- After using Stream for many years, does collect still have these "saucy operations"?
- 设置海思芯片MMZ内存、OS内存详解
- TiKV & TiFlash 加速复杂业务查询丨TiFlash 应用实践
- C专家编程 第1章 C:穿越时空的迷雾 1.7 编译限制
- C专家编程 第3章 分析C语言的声明 3.7 typedef struct foo{... foo;}的含义
- 黄致绮 荣获第六季完美童模全球总决赛 全国总冠军
- 如何使用MATLAB绘制极坐标堆叠柱状图
- 我想请问下,我们的数据库是在亚马逊,Dataworks 连不通,怎么办?
- smp,numa和mpp体系结构总结
- 纯纯粹粹纯纯粹粹
猜你喜欢

面试不再被吊打!这才是Redis分布式锁的七种方案的正确打开方式

蒋松廷 荣获第六季完美童模全球总决赛 全球总冠军

Description of the functional scenario of "collective storage and general governance" in the data center

C专家编程 第1章 C:穿越时空的迷雾 1.6 它很棒,但它符合标准吗

中小微企业如何简单便捷、低成本实现数字化?360视觉云有妙招
![[Unity Starter Plan] Making RubyAdventure01 - Player Creation & Movement](/img/e9/9bba4f7ecee81ae7ce7e492b54ee11.png)
[Unity Starter Plan] Making RubyAdventure01 - Player Creation & Movement

C专家编程 第1章 C:穿越时空的迷雾 1.9 阅读ANSI C标准,寻找乐趣和裨益

Huawei, Lenovo, BAIC, etc. were selected as the first batch of training bases for "Enterprise Digital Transformation and Security Capability Improvement" by the Ministry of Industry and Information Te
![[Deep Learning] Today's bug (August 2)](/img/c5/c4c6d97276bd9997c49ed886aa24cf.png)
[Deep Learning] Today's bug (August 2)

#夏日挑战赛# HarmonyOS 实现一个绘画板
随机推荐
uniapp隐藏导航栏和横屏显示设置
【翻译】关于扩容一个百万级别用户系统的六个课程
C专家编程 第2章 这不是Bug,而是语言特性 2.4 少做之过
【无标题】
SwinIR combat: record the training process of SwinIR in detail
《社会企业开展应聘文职人员培训规范》团体标准在新华书店上架
CPU个数_核心数_线程数之间的关系
超分重建数据集
掌握Redis的Sentinel哨兵原理,可助你拿到25k的offer
将 Windows 事件日志错误加载到 SQL 表中
通俗理解apt-get 和pip的区别是什么
设置海思芯片MMZ内存、OS内存详解
产品-Axure9英文版,轮播图效果
uniapp的webview滑动缩放
C语言01、数据类型、变量常量、字符串、转义字符、注释
实时渲染流程操作复杂吗,如何实现?
SwinIR实战:如何使用SwinIR和预训练模型实现图片的超分
#夏日挑战赛# HarmonyOS 实现一个绘画板
Components of communication - the drop-down menu
How to analyze the weekly activity rate?