节点JS array.includes无法正常工作 [英] Node JS array.includes not working as expected

查看:261
本文介绍了节点JS array.includes无法正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码应从另一个常量数组中未包含的所有元素中过滤一个动态数组(最多30万个元素):

I have the following code which should filter one dynamic array (up to 300 thousands elements) from all elements not contained in another constant array:

orders[] //  is already filled with data
let materials = [] // create empty array
for (let scheme in schemes) { // loop constant object
    materials.push(schemes[scheme].typeID) // take id and add it to materials array
}
materials = Array.from(new Set(materials)) // filter out duplicates
console.log(materials) // everything looks fine here, 83 unique ids
for (let order in orders) { // now loop the main array
    if (!materials.includes(orders[order].type_id)) { // if order's containment id is not found in materials array
        orders.splice(order,1) // remove it from array
        order -= 1 // and one step back to compensate removed index (do I need it or is it processed normally even after .splice?) 
    }
}
// and send filtered orders into browser when certain url is requested

但是,并不是所有不必要的记录都被过滤掉了,有很多

However not all unnecessaty records are filtered out, there are lots and lots of them whose id cannot be found in materials array.

我的错误是什么,错误在哪里?

What is my mistake and where is error?

推荐答案

for (let scheme in schemes) 

这就是您如何遍历对象中的键的方式。而是遍历数组中的条目:

Thats how you iterate over keys in an object. Rather iterate over the entries in an array:

for (let scheme of schemes) 

另外,您应该考虑使用Set进行查找,因为它的查找速度更快。而 map filter 可能会有用:

Additionally you should consider using the Set for lookup as its much faster. And map and filter might be useful:

const materials = new Set(schemes.map(scheme => scheme.typeID));

orders = orders.filter(el => materials.has(el.type_id));

这篇关于节点JS array.includes无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆