javascript - 如何使用下划线 + ES 6 设计更高效的循环

标签 javascript jquery ecmascript-6 underscore.js

下面是我的两个数组。

let clientCollection = ["1","ABC","X12","OE2","PQ$"];



let serverCollection = [{
    "Id": "1",
    "Name": "Ram",
    "Other": "Other properties"

},
{
    "Id": "ABC",
    "Name": "Shyam",
    "Other": "Other properties"

},
{
    "Id": "OE2",
    "Name": "Mohan",
    "Other": "Other properties"

}]

现在我需要比较以上两个集合并创建两个子数组

let matchedIds = []; 

let unMatchedIds = [];

这就是我目前正在做的事情。

for(let i =0 ; i < clientsCollection.length;i++)
{
    if(_.indexOf(serverCollection, clientCollection[i]) >= 0)
    {
          matchedIds.push(clientCollection[i]);
    }
    else
    { 
        unMatchedIds.push(clientCollection[i]);
    }
}

在我的应用程序中,这些数组的大小可以增加到 1000 或更多。这可能有效率问题

我正在使用下划线并尝试过是否可以获得更好的解决方案但还没有找到。

有人可以建议我是否可以使用 underscore + ES6 以更有效的方式做同样的事情??

最佳答案

我认为,这对于 matchedIds 人口来说是个好方法:

for(let i = serverCollection.length - 1; i >= 0; i--) {
  const id = serverCollection[i]['Id'];
  if(clientCollection.indexOf(id) !== -1) {
    matchedIds.push(id);
  }
}

这是在 matchedIds 完成后用于 unMatchedIds 的:

for (var i = clientCollection.length - 1; i >= 0; i--) {
  if (matchedIds.indexOf(clientCollection[i]) === -1) {
    unMatchedIds.push(clientCollection[i]);
  }
}

filterreduce 等都比基本的 indexOf 快!

UPD 我创建了一个 plunker:https://plnkr.co/edit/UcOv6SquUgC7Szgfn8Wk?p=preview .他说,对于 10000 个项目,此解决方案比此处建议的其他 2 个解决方案快 5 倍。

关于javascript - 如何使用下划线 + ES 6 设计更高效的循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46725450/

相关文章:

javascript - jQuery 数组中的下一个和上一个

javascript - FormPanel 中的 ExtJS FormPanel 失败并显示 "this.body is null"

javascript - 在调用异步函数时通过数组同步循环

javascript - 如何在 Javascript 中创建多维数组?

javascript - 合并对象属性并分配具有不同名称的同级属性

javascript - jQuery 元素值等于 x

php - $.post 返回(空字符串)

jquery - 使用 jQuery 在 Spring Boot +thymeleaf 中发布表单

javascript - ES6 中的导入/导出

javascript - 为什么 Promise 中的resolve()之后没有抛出错误?