【问题标题】:Optimize sorting an Array from another Array优化从另一个数组排序数组
【发布时间】:2018-10-02 01:05:41
【问题描述】:

我有两个数组,一个包含一些项目,另一个包含这些项目的 排序 id,如下所示:

const items = [
    { id: 1, label: 'foo' },
    { id: 2, label: 'bar' },
    { id: 3, label: 'lorem' },
    { id: 4, label: 'ipsum' },
]

const sortedItemIds = [4, 3, 2, 1]

我想要另一个包含按 id 排序的项目的数组,如下所示:

const sortedItems = [
    { id: 4, label: 'ipsum' },
    { id: 3, label: 'lorem' },
    { id: 2, label: 'bar' },
    { id: 1, label: 'foo' },
]

请注意,顺序可能不是什么,不是ascdesc

我编写了这段代码,工作得很好

let sortedItems = []
sortedItemIds.map((itemId, index) => {
    items.map(item) => {
        if (item.id === itemId) {
            sortedItems[index] = item
        }
    }
})

由于嵌套的 Array.map() 函数,我觉得我可能会遇到大量项目的问题

对于这种情况有更好的方法/最佳实践吗?

【问题讨论】:

标签: javascript arrays sorting optimization


【解决方案1】:

您可以创建一个键为 id 的对象,然后使用该对象通过 id 获取值。

const items = [{ id: 1, label: 'foo' },{ id: 2, label: 'bar' },{ id: 3, label: 'lorem' },{ id: 4, label: 'ipsum' }]
const sortedItemIds = [4, 3, 2, 1]

const obj = {}
items.forEach(o => obj[o.id] = o);

const sortedItems = sortedItemIds.map(e => Object.assign({}, obj[e]));
console.log(sortedItems)

【讨论】:

  • Object.assign({}, ...) 在这里似乎没有必要。 OP 没有提到对每个对象执行浅层克隆的任何要求,无论如何,Object.assign() 的使用至少应该有一个简短的解释。
  • 如果项目的id 不是一个Int,而是一个字符串怎么办?如果是 mixed 类型?
  • 没关系,我看不懂你的代码。现在对我来说似乎还不错!
【解决方案2】:

您不需要函数映射来执行此操作,只需使用 find Array.indexOfArray.sort 对其进行排序。

const items = [{ id: 1, label: 'foo' },{ id: 2, label: 'bar' },{ id: 3, label: 'lorem' },{ id: 4, label: 'ipsum' }],
      sortedItemIds = [4, 3, 2, 1];

items.sort((a, b) => sortedItemIds.indexOf(a.id) - sortedItemIds.indexOf(b.id));
console.log(items);
.as-console-wrapper { max-height: 100% !important; top: 0; }

【讨论】:

  • 看起来这个解决方案效果很好。我根据需要对其进行了修改,添加了.slice(),因为我不想更改我的第一个数组。 const sortedItems = items.slice().sort((a, b) => sortedItemIds.indexOf(a.id) - sortedItemIds.indexOf(b.id));.
  • 这样做的效率是 O(n^2 log n),而 @NenadVracar 的答案是 ~O(n),假设密钥查找的时间大致恒定。不完全是优化的实现。
猜你喜欢
  • 2011-07-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-02-12
  • 1970-01-01
  • 1970-01-01
  • 2014-10-25
  • 1970-01-01
相关资源
最近更新 更多