【问题标题】:sort an object array based on property of another object array根据另一个对象数组的属性对对象数组进行排序
【发布时间】:2018-06-13 10:39:27
【问题描述】:

我在 js.dummy 数组中有两个对象数组如下所示。

arr1=[{'id':1,'name':'David'},
      {'id':2,'name':'Miles'},
      {'id':3,'name':'John'},];

arr2=[{'id':2,'age':22},
      {'id':3,'age':18},
      {'id':1,'age':12},];

我可以按照与 arr2 相同的 id 顺序对 arr1 进行排序吗?所以 arr1 变成了

[{'id':2,'name':'Miles'},
      {'id':3,'name':'John'},
      {'id':1,'name':'David'},];

实际的数组每个都有大约 900 个对象。那么有什么有效的方法来实现这一点吗?

【问题讨论】:

    标签: javascript jquery arrays sorting


    【解决方案1】:

    reduce第二个数组到由ids索引的Map,然后在排序时使用Map.get标识id的位置。 Maps 保证了 O(1) 的查找时间:

    const arr1 = [{'id':1,'name':'David'},{'id':2,'name':'Miles'},{'id':3,'name':'John'},];
    const arr2 = [{'id':2,'age':22},{'id':3,'age':18},{'id':1,'age':12},];
    
    const ids = arr2.reduce((map, { id }, i) => map.set(id, i), new Map());
    arr1.sort((a, b) => ids.get(a.id) - ids.get(b.id));
    console.log(arr1);

    不过,900 件物品在现代根本不算多。

    【讨论】:

      【解决方案2】:
      // cache arr1 id to index, id is key, index is value
      let arr1IdToIndex = arr1.reduce((sum, cur, index) => (sum[cur.id] = index, sum), {})
      let result = arr2.map(cur => arr1[arr1IdToIndex[cur.id]])
      arr1 = result
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-06-17
        • 1970-01-01
        • 2021-11-20
        • 2016-06-02
        • 1970-01-01
        • 2017-02-23
        相关资源
        最近更新 更多