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

边栏推荐
- 使用Stream多年,collect还有这些“骚操作”?
- To participate in sweepstakes, incoming new programmers magazine welfare!
- How to write SQL statements in DataWorks monitoring data reaches a certain value to indicate the change of
- To add digital wings to education, NetEase Yunxin released the overall solution of "Internet + Education"
- C专家编程 第1章 C:穿越时空的迷雾 1.7 编译限制
- 使用deepstream消息发送功能的时候,检测框没有检测标签,No text labels of bboxes displayed with osd for deepstream-test5
- C专家编程 第3章 分析C语言的声明 3.2 声明是如何形成的
- 【There is no tracking information for the current branch. Please specify which branch you want to 】
- MySQL相关介绍
- 【LeetCode】899. 有序队列
猜你喜欢
![[Unity Starter Plan] Making RubyAdventure01 - Player Creation & Movement](/img/e9/9bba4f7ecee81ae7ce7e492b54ee11.png)
[Unity Starter Plan] Making RubyAdventure01 - Player Creation & Movement

使用.NET简单实现一个Redis的高性能克隆版(一)

error:Illegal instruction (core dumped),离线下载安装这个other版本numpy

掌握Redis的Sentinel哨兵原理,可助你拿到25k的offer

想进阿里?先来搞懂一下分布式事务

面试突击:什么是粘包和半包?怎么解决?

Components of communication - the drop-down menu
[redis] cache penetration and cache avalanche and cache breakdown solutions

2年开发经验去面试,吊打面试官,即将面试的程序员这些笔记建议复习
![[Unity Getting Started Plan] Basic Concepts (7) - Input Manager & Input Class](/img/a7/950ddc6c9eeaa56fe0c3165d22a7d2.png)
[Unity Getting Started Plan] Basic Concepts (7) - Input Manager & Input Class
随机推荐
【目标检测】Focal Loss for Dense Object Detection
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
设置海思芯片MMZ内存、OS内存详解
2年开发经验去面试,吊打面试官,即将面试的程序员这些笔记建议复习
C# 获取文件名和扩展名(后缀名)
软考 --- 软件工程(1)概念、开发模型
产品-Axure9英文版,轮播图效果
自动化部署+整合SSM项目
C专家编程 第2章 这不是Bug,而是语言特性 2.2 多做之过
【带你了解SDN和网络虚拟化】
How to write SQL statements in DataWorks monitoring data reaches a certain value to indicate the change of
C专家编程 第1章 C:穿越时空的迷雾 1.6 它很棒,但它符合标准吗
我想请问下,我们的数据库是在亚马逊,Dataworks 连不通,怎么办?
How ArkUI adapter somehow the screen
MySQL查询语法
【无标题】
TiKV & TiFlash 加速复杂业务查询丨TiFlash 应用实践
B站回应HR称核心用户是Loser;微博回应宕机原因;Go 1.19 正式发布|极客头条
deepstresam的插件配置说明,通过配置osd,设置字体的背景为透明
面试突击:什么是粘包和半包?怎么解决?