简体   繁体   English

比较两个 arrays 并在新数组中过滤掉重复项

[英]compare two arrays and filter the duplicates out in a new array

I am stuck on this problem.我被困在这个问题上。 I have two arrays (simplified here)我有两个 arrays (这里简化)

const array1 = [1,2,3]
const array2 = [1,2]

I want to create a new array comparing the similar values between them and removing them so the final array would be我想创建一个新数组,比较它们之间的相似值并删除它们,以便最终数组为

const finalArray = [3]

I have tried this among many other combinations of mapping filtering, for loops, I don't remember what else I've tested hence only have this too post我已经在许多其他映射过滤组合中尝试过这个,for循环,我不记得我还测试过什么,因此也只有这个帖子

var finalArray = array1.filter(function (e) {
      return array2.indexOf(e) > -1;
    });

The result of this is just结果只是

[1,2]

Hoping someone can point out a solution, I'm sure it's obvious, but I am scratching my head at this point

you just messed up the meaning of the test, and your code should be:您只是弄乱了测试的含义,您的代码应该是:

array1.filter(function (e) { return array2.indexOf(e) === -1 })

but for this kind of case it is better to use the array.includes method但对于这种情况,最好使用array.includes方法
(and in the case of an array made of objects use the array.some method) (如果是由对象组成的数组,请使用array.some方法)

 const array1 = [1,2,3] const array2 = [1,2] const finalArray = array1.filter(x=>.array2.includes(x)) console.log( finalArray )

This is a douplicate question to How to get the difference between two arrays in JavaScript?这是关于如何在 JavaScript 中获得两个 arrays 之间的区别的重复问题?

Check out Luis Sieira's Answer for all possible set theory solutions查看Luis Sieira 的答案,了解所有可能的集合论解决方案

You could also use a Set to remove duplicate values.您还可以使用Set删除重复值。

Spread both of your arrays into a combined array to form a set.将您的两个 arrays 传播到一个组合数组中以形成一个集合。 Then spread your Set back into an array to have an array with only unique values.然后将您的Set传播回一个数组,以获得一个只有唯一值的数组。

const array1 = [1,2,3]
const array2 = [1,2]

const deduped = [...new Set([...array1, ...array2])]

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

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