【问题标题】:How to sort an array of objects in the same order as an id array如何以与 id 数组相同的顺序对对象数组进行排序
【发布时间】:2020-04-13 11:02:55
【问题描述】:

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

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

我有他们的 ID 数组,它们已经被洗牌了,就像这样:

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

如何对players var 进行排序,以便对象与shuffledIDs 的相应 ID 的顺序相同?

编辑:不同的名字只是为了让玩家与众不同

【问题讨论】:

    标签: javascript arrays sorting object


    【解决方案1】:

    如果你的数据很短,那么你可以用下面的单行排序:

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

    【讨论】:

    • 我认为后者是我所拥有的最有效的方法!非常感谢!
    【解决方案2】:

    可以使用数组.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)

    【讨论】:

      【解决方案3】:

      使用键和值作为随机数组的索引创建对象。 使用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);

      【讨论】:

        【解决方案4】:

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2016-08-12
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多