下面是我的两个数组。
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]);
}
}
filter
、reduce
等都比基本的 indexOf
快!
UPD 我创建了一个 plunker:https://plnkr.co/edit/UcOv6SquUgC7Szgfn8Wk?p=preview .他说,对于 10000 个项目,此解决方案比此处建议的其他 2 个解决方案快 5 倍。
关于javascript - 如何使用下划线 + ES 6 设计更高效的循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46725450/