简体   繁体   English

在 Javascript 中查找多个数组之间的差异

[英]Finding the difference between multiple arrays in Javascript

I'm trying to write a function that takes multiple arrays and returns an array of all elements that are found in only one of the arrays.我正在尝试编写一个函数,该函数接受多个数组并返回一个包含仅在其中一个数组中找到的所有元素的数组。 For example: ([1, 2, 3], [1, 2, 3], [1, 2, 3, 4]) returns [4] and ([1, 2, 3], [1, 2, 3], [1, 2, 3, 4], [5], [6]) returns [4, 5, 6])例如: ([1, 2, 3], [1, 2, 3], [1, 2, 3, 4]) returns [4]([1, 2, 3], [1, 2, 3], [1, 2, 3, 4], [5], [6]) returns [4, 5, 6])

I'm also trying to solve the problem without using any libraries such as lodash.我也在尝试在使用任何库(例如 lodash)的情况下解决该问题。 I don't know if I'm on the right lines with below.我不知道我是否在下面的正确行上。 Any help much appreciated.非常感谢任何帮助。

const difference = (...arrays) => {
  return arrays.reduce((acc, cur) => acc.filter(ele => !cur.includes(ele)))
 }
         

You could check if the index is equal to the last index of a flat array.您可以检查索引是否等于平面数组的最后一个索引。

 const difference = (...arrays) => arrays .flat() .filter((v, _, a) => a.indexOf(v) === a.lastIndexOf(v)); console.log(difference([1, 2, 3], [1, 2, 3], [1, 2, 3, 4])); // [4] console.log(difference([1, 2, 3], [2, 4], [5, 7])); // [1, 3, 4, 5, 7]

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

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