简体   繁体   English

我想通过 javascript 中的两个 arrays 循环推送第三个数组中的唯一元素

[英]I want to push unique elements in 3rd array by loop through two arrays in javascript

I tried using techniques below but did not get the desired result, is there anyone willing to share their knowledge?我尝试使用下面的技术但没有得到想要的结果,有没有人愿意分享他们的知识? It would appreciated:)将不胜感激:)

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);
    }
  });
});

You can use Array.filter and Array.includes like so:您可以像这样使用Array.filterArray.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"]

Edit: const declarations (facepalm)编辑:const 声明(facepalm)

You could put the values in a Set.您可以将值放在一个集合中。 In fact you can use the Set constructor callback to feed it with all the feature values, using flatMap .实际上,您可以使用Set构造函数回调来使用flatMap为其提供所有特征值。 Then only remains to convert that set to an Array (if that is what you need):然后只剩下将该集合转换为数组(如果这是您需要的):

let result = Array.from(new Set(categories.flatMap(({features}) => features)));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM