首页 > 解决方案 > 按特定对象键排序

问题描述

我有一个这样的对象数组:

    const cars = [
    {
        id: 'a1c1',
        position: 3,
        name: 'Car 3',
    },
    {
        id: 'b9f6',
        position: 1,
        name: 'Car 1',
    },
    {
        id: '3b6d',
        position: 2,
        name: 'Car 2',
    },
];

现在我按位置排序,从头到尾,像这样:

const sorted = cars.sort((a, b) => a.position - b.position);

然后我有一个带有等级的对象,这些等级值与汽车对象中的 id 相同:

const carsByRank = {
    good: 'b9f6',
    best: '3b6d',
    average: 'a1c1',
};

我需要从这些数据中得到什么:当我对数据进行排序时,我需要最好的汽车排在第一名,第二名,平均第三名,以及任何其他没有排名的汽车,都在这些之下。我怎样才能做到这一点?

标签: javascriptsorting

解决方案


如果“最好”在前,那是您在内部的第一次检查sort以返回-1(a 在 b 之前)或1(a 在 b 之后)。然后检查“好”,然后检查“平均”。

作为你的前三个,这是最好的、好的和平均的。然后,如果需要,您可以继续按位置订购。

注意: Array.prototype.sort确实返回排序后的数组,但也会修改原始数组

我添加了一些额外的对象以更好地显示排序和后续基于位置的排序。

const cars = [{
    id: 'a1c1',
    position: 3,
    name: 'Car 3',
  },
  {
    id: 'a2a2',
    position: 5,
    name: 'Junker 1'
  },
  {
    id: 'a2a3',
    position: 6,
    name: 'Junker 2'
  },
  {
    id: 'b9f6',
    position: 1,
    name: 'Car 1',
  },
  {
    id: 'a2a4',
    position: 7,
    name: 'Junker 3'
  },
  {
    id: '3b6d',
    position: 2,
    name: 'Car 2',
  },
  {
    id: 'a2a5',
    position: 4,
    name: 'Junker 4'
  },
];

const carsByRank = {
  good: 'b9f6',
  best: '3b6d',
  average: 'a1c1',
};

/* sort is in-place and modifies the array */
cars.sort((a, b) => {
  if (a.id === carsByRank.best) return -1;
  else if (b.id === carsByRank.best) return 1;
  else if (a.id === carsByRank.good) return -1;
  else if (b.id === carsByRank.good) return 1;
  else if (a.id === carsByRank.average) return -1;
  else if (b.id === carsByRank.average) return 1;
  else return a.position - b.position;
});

console.log(cars);


推荐阅读