当前位置:网站首页>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;
});

边栏推荐
- 高薪程序员&面试题精讲系列132之微服务之间如何进行通信?服务熔断是怎么回事?你熟悉Hystrix吗?
- 83. Remove Duplicates from Sorted List
- sibling component communication context
- 掌握Redis的Sentinel哨兵原理,可助你拿到25k的offer
- Excuse me this hologres dimension table is cached?How to Finished
- Detailed explanation of setting HiSilicon MMZ memory and OS memory
- ArkUI如何适配横竖屏
- 高效的组织信息共享知识库是一种宝贵的资源
- LeetCode·1163.按字典序排在最后的子串·最小表示法
- uniapp隐藏导航栏和横屏显示设置
猜你喜欢
随机推荐
面试不再被吊打!这才是Redis分布式锁的七种方案的正确打开方式
#夏日挑战赛#【FFH】OpenHarmony设备开发基础(四)启动流程
protobuf 中数据编码规则
正向代理与反向代理
C专家编程 第3章 分析C语言的声明 3.9 轻松一下---驱动物理实体的软件
如何在 DataWorks 中 写SQL语句监控数据的变化到达一定的值 进行提示
node connection mongoose database process
软考 --- 软件工程(1)概念、开发模型
【系统学习编程-编程入门-全民编程 视频教程】
EasyExcel implements dynamic column parsing and table storage
Big guys.Use flink-cdc-sqlserver version 2.2.0 to read sqlserver2008R
LeetCode·72.编辑距离·动态规划
uniapp的webview滑动缩放
C专家编程 第3章 分析C语言的声明 3.4 通过图标分析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
TiKV & TiFlash 加速复杂业务查询丨TiFlash 应用实践
兄弟组件通信context
MarkDown常用代码片段和工具
华为、联想、北汽等入选工信部“企业数字化转型和安全能力提升”首批实训基地
视频人脸识别和图片人脸识别的关系









