当前位置: 首页 > news >正文

JavaScripts数组里的对象排序的24个方法

1. 使用 Array.prototype.sort()

这是最基本、也是最常用的方法。sort() 方法会原地修改数组,并返回排序后的数组。你需要传入一个比较函数来定义排序逻辑。

const array = [{ name: 'Alice', age: 25 },{ name: 'Bob', age: 22 },{ name: 'Charlie', age: 30 }
];// 按照年龄升序排序
array.sort((a, b) => a.age - b.age);
console.log(array);// 按照名字字母顺序排序
array.sort((a, b) => a.name.localeCompare(b.name));
console.log(array);

2. 使用 Array.prototype.map() 和 Array.prototype.sort()

这种方法适用于当你不想改变原始数组时,可以先创建一个新的数组,然后进行排序。

const array = [{ name: 'Alice', age: 25 },{ name: 'Bob', age: 22 },{ name: 'Charlie', age: 30 }
];const sortedArray = array.map(item => item) // 复制数组.sort((a, b) => a.age - b.age);console.log(sortedArray);
console.log(array); // 原数组未改变

3. 使用 Array.prototype.slice() 和 Array.prototype.sort()

同样是为了不改变原数组,这种方法利用 slice() 创建一个数组的浅拷贝,然后进行排序。

const array = [{ name: 'Alice', age: 25 },{ name: 'Bob', age: 22 },{ name: 'Charlie', age: 30 }
];const sortedArray = array.slice().sort((a, b) => a.age - b.age);
console.log(sortedArray);
console.log(array); // 原数组未改变

4. 使用 Array.prototype.reduce() 实现自定义排序

如果你需要对数组进行复杂的排序操作,可以使用 reduce() 方法。

const array = [{ name: 'Alice', age: 25 },{ name: 'Bob', age: 22 },{ name: 'Charlie', age: 30 }
];const sortedArray = array.reduce((accumulator, currentValue) => {let i = 0;while (i < accumulator.length && accumulator[i].age < currentValue.age) {i++;}accumulator.splice(i, 0, currentValue);return accumulator;
}, []);console.log(sortedArray);

5. 使用第三方库(如 Lodash)

Lodash 提供了更强大的排序功能,如多属性排序。你需要先安装 Lodash:

npm install lodash

然后使用 Lodash 的 _.orderBy 方法:

const _ = require('lodash');const array = [{ name: 'Alice', age: 25 },{ name: 'Bob', age: 22 },{ name: 'Charlie', age: 30 }
];// 按照多个属性排序
const sortedArray = _.orderBy(array, ['age', 'name'], ['asc', 'asc']);
console.log(sortedArray);

6. 使用自定义比较函数进行多字段排序

如果你希望根据多个字段进行排序,可以编写自定义的比较函数。

const array = [{ name: 'Alice', age: 25, height: 165 },{ name: 'Bob', age: 22, height: 175 },{ name: 'Charlie', age: 22, height: 170 }
];// 按年龄升序,如果年龄相同按身高降序
array.sort((a, b) => {if (a.age !== b.age) {return a.age - b.age; // 年龄升序} else {return b.height - a.height; // 年龄相同,身高降序}
});console.log(array);

7. 使用稳定排序库(如 array-stable)

在某些情况下,你可能需要一个稳定的排序算法。JavaScript 的原生 sort() 方法在不同浏览器上可能不是稳定的。可以使用 array-stable 库来确保稳定排序。

安装该库:

npm install array-stable

使用示例:

const stable = require('array-stable'); // 导入稳定排序库const array = [{ name: 'Alice', age: 25 },{ name: 'Bob', age: 22 },{ name: 'Charlie', age: 30 }
];stable.sort(array, (a, b) => a.age - b.age); // 按年龄升序稳定排序
console.log(array);

8. 使用 Intl.Collator 进行本地化排序

对于字符串排序,特别是涉及到国际化时,可以使用 Intl.Collator 来处理。

const array = [{ name: 'Éclair', age: 25 },{ name: 'Alice', age: 22 },{ name: 'Bob', age: 30 }
];const collator = new Intl.Collator('fr', { sensitivity: 'base' }); // 创建法语语言环境的排序器
array.sort((a, b) => collator.compare(a.name, b.name)); // 按名称排序
console.log(array);

9. 使用 Proxy 对象包装数组

如果你希望在数组排序前后做一些额外操作,可以使用 Proxy 对象。

const array = [{ name: 'Alice', age: 25 },{ name: 'Bob', age: 22 },{ name: 'Charlie', age: 30 }
];const handler = {set(target, property, value) {console.log(`Setting value ${value} on property ${property}`);target[property] = value;return true;}
};const proxyArray = new Proxy(array, handler); // 使用 Proxy 包装数组
proxyArray.sort((a, b) => a.age - b.age); // 对代理数组进行排序
console.log(proxyArray);

10. 使用 TypedArray 进行数值排序

如果数组中的对象包含大量数值,并且排序性能非常关键,可以考虑将数值提取到 TypedArray 中进行排序,然后映射回原数组。

const array = [{ name: 'Alice', age: 25 },{ name: 'Bob', age: 22 },{ name: 'Charlie', age: 30 }
];const ages = new Uint8Array(array.map(item => item.age)); // 提取年龄到 Uint8Array 中
const sortedIndices = Array.from(ages).map((age, index) => ({ age, index })).sort((a, b) => a.age - b.age).map(item => item.index);const sortedArray = sortedIndices.map(index => array[index]); // 根据排序后的索引重构数组
console.log(sortedArray);

11. 按照对象属性值的字符串长度排序

const array = [{ name: 'Alice', description: 'A short description' },{ name: 'Bob', description: 'A very long and detailed description' },{ name: 'Charlie', description: 'Medium description' }
];// 按描述的长度升序排列
array.sort((a, b) => a.description.length - b.description.length);console.log(array);

12. 按照日期字段进行排序

const array = [{ event: 'Event 1', date: new Date('2023-05-01') },{ event: 'Event 2', date: new Date('2022-08-15') },{ event: 'Event 3', date: new Date('2024-01-10') }
];// 按日期升序排列
array.sort((a, b) => a.date - b.date);console.log(array);

13. 使用 reduce 和 Object.entries 对对象数组进行排序

const array = [{ name: 'Alice', age: 25 },{ name: 'Bob', age: 22 },{ name: 'Charlie', age: 30 }
];// 使用 reduce 和 Object.entries 对对象数组按年龄升序排序
const sortedArray = Object.values(array.reduce((acc, obj) => {acc[obj.age] = obj;return acc;
}, {}));console.log(sortedArray);

14. 按照多个条件进行复杂排序

const array = [{ name: 'Alice', age: 25, height: 165 },{ name: 'Bob', age: 22, height: 175 },{ name: 'Charlie', age: 22, height: 170 },{ name: 'David', age: 22, height: 175 }
];// 按年龄升序,如果年龄相同,再按身高降序,如果年龄和身高都相同,再按姓名字母升序
array.sort((a, b) => {if (a.age !== b.age) {return a.age - b.age; // 年龄升序} else if (a.height !== b.height) {return b.height - a.height; // 身高降序} else {return a.name.localeCompare(b.name); // 姓名字母升序}
});console.log(array);

15. 基于对象某一属性的数值范围排序

const array = [{ name: 'Alice', score: 85 },{ name: 'Bob', score: 75 },{ name: 'Charlie', score: 95 },{ name: 'David', score: 80 }
];// 按分数区间排序:低于80分、80到90分之间、大于90分
array.sort((a, b) => {if (a.score < 80 && b.score >= 80) {return -1; // a 在 b 之前} else if (a.score >= 80 && a.score <= 90 && (b.score < 80 || b.score > 90)) {return -1; // a 在 b 之前} else if (a.score > 90 && b.score <= 90) {return 1; // a 在 b 之后} else {return 0;}
});console.log(array);

16. 使用 Map 进行自定义键排序

const array = [{ name: 'Alice', priority: 'medium' },{ name: 'Bob', priority: 'low' },{ name: 'Charlie', priority: 'high' },{ name: 'David', priority: 'medium' }
];const priorityOrder = new Map([['low', 1],['medium', 2],['high', 3]
]);// 按优先级排序
array.sort((a, b) => priorityOrder.get(a.priority) - priorityOrder.get(b.priority));console.log(array);

17. 按照嵌套对象属性排序

const array = [{ id: 1, details: { age: 25 } },{ id: 2, details: { age: 30 } },{ id: 3, details: { age: 20 } }
];// 按嵌套对象的年龄属性升序排序
array.sort((a, b) => a.details.age - b.details.age);console.log(array);

18. 按照字符串中的数字进行排序

const array = ['item20', 'item5', 'item12', 'item1'];// 按字符串中的数字部分进行升序排序
array.sort((a, b) => {const numA = parseInt(a.replace(/\D/g, ''));const numB = parseInt(b.replace(/\D/g, ''));return numA - numB;
});console.log(array);

19. 按照布尔值进行排序

const array = [{ name: 'Alice', isActive: true },{ name: 'Bob', isActive: false },{ name: 'Charlie', isActive: true },{ name: 'David', isActive: false }
];// 按布尔值排序,false 在前,true 在后
array.sort((a, b) => a.isActive - b.isActive);console.log(array);

20. 按照多个对象数组的属性组合排序

const array = [{ firstName: 'Alice', lastName: 'Smith' },{ firstName: 'Bob', lastName: 'Brown' },{ firstName: 'Charlie', lastName: 'Smith' },{ firstName: 'David', lastName: 'Johnson' }
];// 先按姓氏排序,如果姓氏相同,再按名字排序
array.sort((a, b) => {if (a.lastName !== b.lastName) {return a.lastName.localeCompare(b.lastName); // 按姓氏排序} else {return a.firstName.localeCompare(b.firstName); // 按名字排序}
});console.log(array);

21. 基于自定义权重排序

const array = [{ name: 'Alice', role: 'user' },{ name: 'Bob', role: 'admin' },{ name: 'Charlie', role: 'guest' },{ name: 'David', role: 'user' }
];const roleWeights = {'guest': 1,'user': 2,'admin': 3
};// 按角色权重排序
array.sort((a, b) => roleWeights[a.role] - roleWeights[b.role]);console.log(array);

22. 按照随机顺序排序

const array = [1, 2, 3, 4, 5];// 使用 Math.random() 将数组随机打乱
array.sort(() => Math.random() - 0.5);console.log(array);

23. 按照数组中对象的多个数值属性排序

const array = [{ name: 'Alice', score1: 90, score2: 85 },{ name: 'Bob', score1: 85, score2: 95 },{ name: 'Charlie', score1: 80, score2: 75 },{ name: 'David', score1: 90, score2: 80 }
];// 先按 score1 排序,如果 score1 相同,再按 score2 排序
array.sort((a, b) => {if (a.score1 !== b.score1) {return a.score1 - b.score1; // 按 score1 排序} else {return a.score2 - b.score2; // 按 score2 排序}
});console.log(array);

24. 按照对象属性的存在性排序

const array = [{ name: 'Alice', age: 25 },{ name: 'Bob' },{ name: 'Charlie', age: 30 },{ name: 'David' }
];// 有 age 属性的对象在前,没有的在后
array.sort((a, b) => ('age' in a ? -1 : 1) - ('age' in b ? -1 : 1));console.log(array);

相关文章:

JavaScripts数组里的对象排序的24个方法

1. 使用 Array.prototype.sort() 这是最基本、也是最常用的方法。sort() 方法会原地修改数组&#xff0c;并返回排序后的数组。你需要传入一个比较函数来定义排序逻辑。 const array [{ name: Alice, age: 25 },{ name: Bob, age: 22 },{ name: Charlie, age: 30 } ];// 按照…...

Mongodb介绍及window环境安装

本文主要内容为nosql数据库-MongoDB介绍及window环境安装。 目录 什么是MongoDB&#xff1f; 主要特点 MongoDB 与Mysql对应 安装MongoDB 下载MongoDB 自定义安装 创建目录 配置环境变量 配置MongoDB服务 服务改为手动 启动与关闭 安装MongoDB Shell 下载安装包 …...

Spring响应式编程之Reactor核心组件

Reactor核心组件 Flux和Mono组件&#xff08;1&#xff09;Flux组件&#xff08;2&#xff09;Mono组件 Flux和Mono组件 Reactor 框架提供了两个核心组件来发布数据&#xff0c;分别是 Flux 和 Mono 组件。两者都是实现Publisher接口的高级抽象&#xff0c;可以说是应用程序开…...

动手学深度学习(Pytorch版)代码实践 -计算机视觉-37微调

37微调 import os import torch import torchvision from torch import nn import liliPytorch as lp import matplotlib.pyplot as plt from d2l import torch as d2l# 获取数据集 d2l.DATA_HUB[hotdog] (d2l.DATA_URL hotdog.zip,fba480ffa8aa7e0febbb511d181409f899b9baa5…...

视频监控平台:支持交通部行业标准JT/T905协议(即:出租汽车服务管理信息系统)的源代码的函数和功能介绍及分享

目录 一、视频监控平台介绍 &#xff08;一&#xff09;概述 &#xff08;二&#xff09;视频接入能力介绍 &#xff08;三&#xff09;功能介绍 二、JT/T905协议介绍 &#xff08;一&#xff09;概述 &#xff08;二&#xff09;主要内容 1、设备要求 2、业务功能要求…...

【jenkins1】gitlab与jenkins集成

文章目录 1.Jenkins-docker配置&#xff1a;运行在8080端口上&#xff0c;机器只要安装docker就能装载image并运行容器2.Jenkins与GitLab配置&#xff1a;docker ps查看正在运行&#xff0c;浏览器访问http://10....:8080/2.1 GitLab与Jenkins的Access Token配置&#xff1a;不…...

边缘计算设备有哪些

边缘设备是指那些位于数据源附近&#xff0c;能够执行数据处理、分析和决策的计算设备。这些设备通常具有一定的计算能力、存储能力和网络连接能力&#xff0c;能够减少数据传输到云端的需要&#xff0c;从而降低延迟、节省带宽并提高数据处理的效率。以下是一些常见的边缘设备…...

C++初学者指南第一步---7.控制流(基础)

C初学者指南第一步—7.控制流&#xff08;基础&#xff09; 文章目录 C初学者指南第一步---7.控制流&#xff08;基础&#xff09;1.术语:表达式/语句Expressions表达式Statements语句 2.条件分支3.Switching(切换):基于值的分支4.三元条件运算符5.循环迭代基于范围的循环   C…...

MFC学习--CListCtrl复选框以及选择

如何展示复选框 //LVS_EX_CHECKBOXES每一行的最前面带个复选框//LVS_EX_FULLROWSELECT整行选中//LVS_EX_GRIDLINES网格线//LVS_EX_HEADERDRAGDROP列表头可以拖动m_listctl.SetExtendedStyle(LVS_EX_FULLROWSELECT | LVS_EX_CHECKBOXES | LVS_EX_GRIDLINES); 全选&#xff0c;全…...

如何与PM探讨项目

我曾在2020年撰写过一篇名为对产品经理的一些思考的文章&#xff0c;紧接着在2021年&#xff0c;我又写了一篇对如何分析项目的思考。在这两篇文章中&#xff0c;我提出了一个核心观点&#xff1a;“船长需要把控所有事情&#xff0c;但最核心的是&#xff1a;需要知道目标是什…...

今年618各云厂商的香港服务器优惠活动汇总

又到了一年618年中钜惠活动时间&#xff0c;2024年各大云服务器厂商都有哪些活动呢&#xff1f;有哪些活动包括香港服务器呢&#xff1f;带着这些问题&#xff0c;小编给大家一一讲解各大知名厂商的618活动有哪些值得关注的地方&#xff0c;如果对你有帮助&#xff0c;欢迎点赞…...

Android平台下VR头显如何低延迟播放4K以上超高分辨率RTSP|RTMP流

技术背景 VR头显需要更高的分辨率以提供更清晰的视觉体验、满足沉浸感的要求、适应透镜放大效应以及适应更广泛的可视角度&#xff0c;超高分辨率的优势如下&#xff1a; 提供更清晰的视觉体验&#xff1a;VR头显的分辨率直接决定了用户所看到的图像的清晰度。更高的分辨率意…...

WHAT - NextJS 系列之 Rendering - Server Components

目录 一、Server Components1.1 Server Components特点使用 1.2 Client Components特点使用 1.3 综合使用示例1.4 小结 二、Server Components 优势三、Streaming 特性3.1 基本介绍和使用Streaming的理解工作原理使用示例服务器端组件客户端组件页面流程解释 3.2 HTTP/1.1和HTT…...

Web项目部署后浏览器刷新返回Nginx的404错误对应解决方案

data: 2024/6/22 16:05:34 周六 limou3434 叠甲&#xff1a;以下文章主要是依靠我的实际编码学习中总结出来的经验之谈&#xff0c;求逻辑自洽&#xff0c;不能百分百保证正确&#xff0c;有错误、未定义、不合适的内容请尽情指出&#xff01; 文章目录 1.源头2.排错3.原因4.解…...

视频与音频的交响:探索达摩院VideoLLaMA 2的技术创新

一、简介 文章&#xff1a;https://arxiv.org/abs/2406.07476 代码&#xff1a;https://github.com/DAMO-NLP-SG/VideoLLaMA2 VideoLLaMA 2是由阿里巴巴集团的DAMO Academy团队开发的视频大型语言模型&#xff08;Video-LLM&#xff09;&#xff0c;旨在通过增强空间-时间建模…...

更改ip后还被封是ip质量的原因吗?

不同的代理IP的质量相同&#xff0c;一般来说可以根据以下几个因素来进行判断&#xff1a; 1.可用率 可用率就是提取的这些代理IP中可以正常使用的比率。假如我们无法使用某个代理IP请求目标网站或者请求超时&#xff0c;那么就代表这个代理不可用&#xff0c;一般来说免费代…...

【Oracle】调用HTTP接口

Oracle调用http接口 前情提要1.创建HTTP请求函数2.创建ACL并授予权限3.测试HTTP请求函数其他操作 一点建议参考文档 前情提要 公司唯有oracle被允许访问内外网&#xff0c;因此在oracle中发起HTTP请求。 1.创建HTTP请求函数 CREATE OR REPLACE FUNCTION HTTP_REQUEST(v_url …...

Minillama3->sft训练

GitHub - leeguandong/MiniLLaMA3: llama3的迷你版本,包括了数据,tokenizer,pt的全流程llama3的迷你版本,包括了数据,tokenizer,pt的全流程. Contribute to leeguandong/MiniLLaMA3 development by creating an account on GitHub.https://github.com/leeguandong/MiniLL…...

【教师资格证考试综合素质——法律专项】学生伤害事故处理办法以及未成人犯罪法笔记相关练习题

目录 《学生伤害事故处理办法》 第一章 总 则 第二章 事故与责任 &#xff08;谁有错&#xff0c;谁担责&#xff09; 第三章 事故处理程序 第四章 事故损害的赔偿 第五章 事故责任者的处理 第六章 附 则 《中华人民共和国预防未成人犯罪法》 第一章 总 则 第二章 预…...

Vite: 关于静态资源的处理机制

概述 随着前端技术的飞速发展&#xff0c;项目规模和复杂度不断增加&#xff0c;如何高效地处理静态资源成为了提升开发效率和应用性能的关键Vite&#xff0c;作为新一代前端构建工具&#xff0c;以其轻量级、快速启动和热更新著称&#xff0c;同时也为静态资源的管理和优化提…...

LeetCode26. 删除有序数组中的重复项 27. 移除元素 35. 搜索插入位置 数组,双指针 二分查找

给你一个 非严格递增排列 的数组 nums &#xff0c;请你 原地 删除重复出现的元素&#xff0c;使每个元素 只出现一次 &#xff0c;返回删除后数组的新长度。元素的 相对顺序 应该保持 一致 。然后返回 nums 中唯一元素的个数。考虑 nums 的唯一元素的数量为 k。去重后&#xf…...

RMBG-2.0实测参数详解:batch_size=1/resize=1024/alpha_threshold=0.5设定依据

RMBG-2.0实测参数详解&#xff1a;batch_size1/resize1024/alpha_threshold0.5设定依据 1. 项目背景与核心价值 RMBG-2.0&#xff08;BiRefNet&#xff09;是目前开源领域最强大的图像抠图模型之一&#xff0c;它在处理复杂边缘细节方面表现出色&#xff0c;特别是对于毛发、…...

[特殊字符] GLM-4V-9B企业级方案:客户上传截图问题自动诊断

GLM-4V-9B企业级方案&#xff1a;客户上传截图问题自动诊断 1. 引言 想象一下这个场景&#xff1a;你是一家SaaS公司的技术支持工程师&#xff0c;每天的工作就是处理海量的客户工单。其中&#xff0c;有相当一部分问题描述是模糊的&#xff0c;比如“我的页面显示不正常”、…...

牙齿龋齿检测数据集 YOLO模型如何训练牙齿病害数据集 权重识别龋齿

牙齿龋齿检测数据集&#xff0c;2554张&#xff0c;提供yolo和voc两种标注方式 1类&#xff0c;标注数量&#xff1a; caries: 6946 image num: 2554 &#x1f9b7; 龋齿检测数据集 (Dental Caries Detection Dataset) 属性详细描述数据集名称齿科龋齿目标检测数据集图像总数2…...

电商客服外包怎么选|避坑指南[特殊字符]2026 商家必看

做电商绕不开客服外包&#xff0c;但低价陷阱、转包兼职、大促掉链、响应超时、售后甩锅真的太坑了&#xff01;今天整理一套不踩雷选型攻略&#xff0c;全是行业干货&#xff0c;新手也能直接抄作业&#x1f447; &#x1f6ab;先避坑&#xff1a;这些雷区千万别碰 超低价诱惑…...

从抓包实战到协议栈:深入解析DDS核心报文与通信机制

1. 从HelloWorld抓包开始认识DDS 第一次接触DDS协议时&#xff0c;很多人会被各种专业术语搞得晕头转向。其实最快的学习方式就是从实际案例入手——就像我当初用Fast DDS的HelloWorld示例做实验那样。这个经典案例包含一个发布者和一个订阅者&#xff0c;正好能展示DDS最核心…...

保姆级教程:手把手教你用Zabbix监控MySQL数据库(Percona模板实战)

深度实战&#xff1a;基于Percona模板构建企业级MySQL监控体系 当数据库规模突破百万级QPS时&#xff0c;传统的手动检查方式就像用体温计测量森林大火——既低效又危险。去年某电商大促期间&#xff0c;我们曾因未及时发现连接数耗尽导致核心交易库雪崩&#xff0c;这个教训让…...

如何高效保存B站视频?全功能跨平台工具BiliTools使用指南

如何高效保存B站视频&#xff1f;全功能跨平台工具BiliTools使用指南 【免费下载链接】BiliTools A cross-platform bilibili toolbox. 跨平台哔哩哔哩工具箱&#xff0c;支持下载视频、番剧等等各类资源 项目地址: https://gitcode.com/GitHub_Trending/bilit/BiliTools …...

Graphormer一文详解:RDKit+PyG+Gradio技术栈整合与Supervisor服务管理

Graphormer一文详解&#xff1a;RDKitPyGGradio技术栈整合与Supervisor服务管理 1. 项目概述 Graphormer是一种基于纯Transformer架构的图神经网络模型&#xff0c;专门为分子图&#xff08;原子-键结构&#xff09;的全局结构建模与属性预测而设计。该模型在OGB、PCQM4M等分…...

【Python内存管理黄金法则】:20年SRE亲授生产环境OOM崩溃前的5个关键干预点

第一章&#xff1a;Python智能体内存管理策略的底层认知与生产意义Python智能体&#xff08;如基于LLM的Agent系统&#xff09;在长时间运行、多轮对话与状态缓存场景下&#xff0c;内存行为远超传统脚本应用。其内存压力不仅来自模型权重加载&#xff0c;更源于动态生成的中间…...