首页 > 解决方案 > 按任意对象值对数组进行排序(不是升序或降序)

问题描述

您好,这是一个相当复杂的问题。

我有一个对象数组:

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 发布了一个可行的解决方案!谢谢你

标签: javascriptarrayssorting

解决方案


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);


推荐阅读