如何以与id数组相同的顺序对对象数组进行排序

时间:2020-04-13 11:02:55

标签: javascript arrays sorting object

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

    var players = [{
        id: "thisIsID1",
        name: "William",
        otherProps
    },
    {
        id: "thisIsID2",
        name: "Shakespeare",
        otherProps
    },
    {
        id: "thisIsID3",
        name: "Lola",
        otherProps
    }]

我有一个和他们的ID数组,它们已经改组,就像这样:

var shuffledIDs = ["thisIsID2", "thisIsID3", "thisIsID1"]

如何对players变量进行排序,使对象与shuffledIDs的相应ID的顺序相同?

编辑:只是为了使玩家与众不同而使用不同的名称

4 个答案:

答案 0 :(得分:4)

如果您的数据很短,则可以使用以下单行代码对其进行排序:

players = shuffledIDs.map(id => players.find(v => v.id == id))

基本上,对于shuffledID中的每个id,它都会在players中找到具有该id的元素,并将其放在正确的位置。但是,这需要O(n ^ 2)时间,因此对于较大的数据可能无法很好地扩展。如果需要更快的方法,可以维护一个ID对象:

var ids = {};
players.forEach(v => ids[v.id] = v);
players = shuffledIDs.map(v => ids[v]);

答案 1 :(得分:1)

您可以使用数组.find()方法来实现它:

var players = [{
        id: "thisIsID1",
        name: "William"
    },
    {
        id: "thisIsID2",
        name: "Shakespeare"
    },
    {
        id: "thisIsID3",
        name: "Lola"
    }]

var shuffledIDs = ["thisIsID2", "thisIsID3", "thisIsID1"]
var result = shuffledIDs.map(x => players.find(p=>p.id === x))
console.log(result)

答案 2 :(得分:1)

创建带有键和值的对象作为随机播放数组的索引。 使用sort方法并优先于改组索引之上的基础。即使播放器中有重复数据,这种方式也应如此。

var players = [
  {
    id: "thisIsID1",
    name: "William"
  },
  {
    id: "thisIsID2",
    name: "Shakespeare"
  },
  {
    id: "thisIsID3",
    name: "Lola"
  }
];

const shuffleIds = ["thisIsID2", "thisIsID3", "thisIsID1"];

const shuf_idx = Object.fromEntries(shuffleIds.map((x, i) => [x, i]));

players.sort((a, b) => shuf_idx[a.id] - shuf_idx[b.id]);

console.log(players);

答案 3 :(得分:0)

.map().find()中使用元素索引:

const shuffledIDs = ["thisIsID2", "thisIsID3", "thisIsID1"];
const players = [{ id: "thisIsID1", name: "William" }, { id: "thisIsID2",       name: "Shakespeare" }, { id: "thisIsID3", name: "Lola" }];

const result = players.map((e, i) => players.find(f => f.id === shuffledIDs[i]));

console.log(result);