javascript - 按任意对象值对数组进行排序(不是升序或降序)
问题描述
您好,这是一个相当复杂的问题。
我有一个对象数组:
let animals = [
{
"typ": "rats",
"name": "RB 1",
},
{
"typ": "mice",
"name": "MB 1",
},
{
"typ": "rats",
"name": "RB 4",
},
{
"typ": "rats",
"name": "RB 2",
},
{
"typ": "rats",
"name": "RB 3",
},
{
"typ": "mice",
"name": "MB 2",
},
{
"typ": "mice",
"name": "MB 3",
}
这个数组最多可以有几百个对象和其他几种动物!!!
现在我想对其进行排序,以便我首先拥有所有老鼠,然后是所有老鼠......
第二步是按名称对所有大鼠和小鼠进行排序,例如 RB 1 、 RB2 、 RB 3 .... 这样我就得到了一个这样的数组
[
{
"typ": "rats",
"name": "RB 1",
},
{
"typ": "rats",
"name": "RB 2",
},
{
"typ": "rats",
"name": "RB 3",
},
{
"typ": "rats",
"name": "RB 4",
},
{
"typ": "mice",
"name": "MB 1",
},
{
"typ": "mice",
"name": "MB 2",
},
{
"typ": "mice",
"name": "MB 3",
}]
我使用 snapshotChanges() 从 firestore 集合中获取初始数组,因此对象(firestore 数据库中的文档)都以随机顺序出现
谢谢大家
编辑:
@secan 发布了一个可行的解决方案!谢谢你
解决方案
let animals = [{
"typ": "rats",
"name": "RB 1",
},
{
"typ": "mice",
"name": "MB 1",
},
{
"typ": "rats",
"name": "RB 4",
},
{
"typ": "rats",
"name": "RB 2",
},
{
"typ": "rats",
"name": "RB 3",
},
{
"typ": "mice",
"name": "MB 2",
},
{
"typ": "mice",
"name": "MB 3",
},
{
"typ": "monkeys",
"name": "MoB 2",
},
{
"typ": "monkeys",
"name": "MoB 1",
}
];
let animalsPriority = ['monkeys', 'rats', 'mice'];
const sortedAnimals = animals.sort((a, b) => {
return (
(animalsPriority.indexOf(a.typ) < animalsPriority.indexOf(b.typ) && -1) ||
(animalsPriority.indexOf(a.typ) > animalsPriority.indexOf(b.typ) && 1) ||
(a.name < b.name && -1) ||
(a.name > b.name && 1) ||
0
);
});
console.log(sortedAnimals);
推荐阅读
- dart - 在 TabBarView 中颤振 video_player
- asp.net-mvc - 使用具有日期和时间的数字签名生成和签署 PDF
- nginx - Nuxt js 网站在其他国家不起作用
- javascript - UnhandledPromiseRejectionWarning 异步等待
- c++ - 使用基本 CRC C++ 子例程实现 CCSDS BCH(64,56) FEC 代码
- python - 当用户遇到带有所有请求值的错误(POST/GET)时,Flask 发送电子邮件
- excel - 编写的宏代码没有给我预期的结果
- c# - INotifyPropertyChanged 和 InotfyCollectionChanged 实现
- .net - 事件中心连接池
- latex - 如何将特定小节中的文本更改为斜体?