![](/img/trans.png)
[英]Javascript: Loop Through Two Arrays and Sum Elements in Array Via Function
[英]I want to push unique elements in 3rd array by loop through two arrays in javascript
我尝试使用下面的技术但没有得到想要的结果,有没有人愿意分享他们的知识? 将不胜感激:)
for (let i = 0; i < categories.length; i++) {
for (let j = 0; j < categories[i].features.length - 1; j++) {
if (categories[i].features[j] !== categories[i].features[j+ 1]) {
newCataegories.push(categories[i].features[j]);
console.log(categories[i].features[j].id, j);
}
}
}
categories.forEach((element, index) => {
element.features.forEach((e, i) => {
if (newCataegories.indexOf(e) === -1) {
newCataegories.push(e);
}
});
});
您可以像这样使用Array.filter
和Array.includes
:
const array1 = ["a", "b", "c", "d"]
const array2 = ["a", "c"]
// Filter the array by making sure the item isn't in array 2
const array3 = array1.filter((item) => !array2.includes(item))
console.log(array3) // ["b", "d"]
编辑:const 声明(facepalm)
您可以将值放在一个集合中。 实际上,您可以使用Set
构造函数回调来使用flatMap
为其提供所有特征值。 然后只剩下将该集合转换为数组(如果这是您需要的):
let result = Array.from(new Set(categories.flatMap(({features}) => features)));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.