当前位置:网站首页>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;
});
边栏推荐
- TiKV & TiFlash 加速复杂业务查询丨TiFlash 应用实践
- WordPress建站技术笔记
- 83. Remove Duplicates from Sorted List
- Kubernetes 笔记 / 入门 / 生产环境 / 用部署工具安装 Kubernetes / 用 kubeadm 启动集群 / 安装 kubeadm
- 关于oracle表空间在线碎片整理
- B站回应HR称核心用户是Loser;微博回应宕机原因;Go 1.19 正式发布|极客头条
- Hannah荣获第六季完美童模全球总决赛全球人气总冠军
- 将 Windows 事件日志错误加载到 SQL 表中
- MATLAB | 七夕节快到了,还不给朋友安排上这个咕呱小青蛙?
- C专家编程 第1章 C:穿越时空的迷雾 1.6 它很棒,但它符合标准吗
猜你喜欢
随机推荐
C专家编程 第2章 这不是Bug,而是语言特性 2.2 多做之过
MySQL窗口函数 PARTITION BY()函数介绍
Cookie和Session的关系
Kubernetes 笔记 / 任务 / 管理集群 / 用 kubeadm 管理集群 / 配置一个 cgroup 驱动
phoenix创建映射表和创建索引、删除索引
C专家编程 第2章 这不是Bug,而是语言特性 2.3 误做之过
如何在 DataWorks 中 写SQL语句监控数据的变化到达一定的值 进行提示
如何选择合适的导电滑环型号
[Unity Getting Started Plan] Basic Concepts (6) - Sprite Renderer Sprite Renderer
通俗理解apt-get 和pip的区别是什么
C专家编程 第3章 分析C语言的声明 3.7 typedef struct foo{... foo;}的含义
Understand the recommendation system in one article: Outline 02: The link of the recommendation system, from recalling rough sorting, to fine sorting, to rearranging, and finally showing the recommend
leetcode SVM
C语言02、语句、函数
大佬们。使用flink-cdc-sqlserver 2.2.0 版本读取sqlserver2008R
纯纯粹粹纯纯粹粹
面试突击71:GET 和 POST 有什么区别?
vector类
实时渲染流程操作复杂吗,如何实现?
兄弟组件通信context