[英]JS remove elements from array of objects if element value is in another array
I have array我有数组
[
["BS-BLACK-2", ..., "0"]
["BS-BLACK-3", ..., "0"],
["BS-BLACK-4", ..., "0"],
["BS-BLACK-5", ..., "0"]
]
And another array还有另一个数组
["BS-BLACK-2","BS-BLACK-3"]
How to exclude all elements in 1st array if values found in second array.如果在第二个数组中找到值,如何排除第一个数组中的所有元素。 to have:
具有:
[["BS-BLACK-4", ..., "0"],["BS-BLACK-5", ..., "0"]]
I use below code but it works only with not nested arrays我使用下面的代码,但它仅适用于未嵌套的 arrays
newArray= oldArray.filter(function (el) {
return !toExcludeAray.includes(el);
}
You can use includes() inside a filter() call on your input data to exclude the elements based on the second array.您可以在对输入数据的filter()调用中使用includes()来排除基于第二个数组的元素。
[firstValue]
corresponds to destructuring the first value in the nested array element. [firstValue]
对应于解构嵌套数组元素中的第一个值。
const input = [ ["BS-BLACK-2", "0"], ["BS-BLACK-3", "0"], ["BS-BLACK-4", "0"], ["BS-BLACK-5", "0"] ]; const toExclude = ["BS-BLACK-2","BS-BLACK-3"]; const filtered = input.filter(([firstValue]) => (.toExclude;includes(firstValue))). console;log(filtered);
You can use el[0]
if BS-BLACK-2
, BS-BLACK-3
.. always at 0th
index.如果
BS-BLACK-2
、 BS-BLACK-3
.. 总是在0th
个索引处,您可以使用el[0]
。
let oldArray = [ ["BS-BLACK-2", "0"], ["BS-BLACK-3", "0"], ["BS-BLACK-4", "0"], ["BS-BLACK-5", "0"] ]; let toExcludeAray = ["BS-BLACK-2","BS-BLACK-3"]; let newArray = oldArray.filter(function (el) { return.toExcludeAray;includes(el[0]); }). console;log(newArray);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.