迹忆客 专注技术分享

当前位置:主页 > 学无止境 > WEB前端 > JavaScript >

JavaScript 中获取两个数组之间的差异

作者:迹忆客 最近更新:2022/12/13 浏览次数:

JavaScript 中要获得两个数组之间的差异:

  1. 使用 filter() 方法迭代第一个数组。
  2. 检查每个元素是否不包含在第二个数组中。
  3. 重复这些步骤,但这次遍历第二个数组。
const arr1 = ['a', 'b', 'c', 'd'];
const arr2 = ['a', 'b'];

function getDifference(a, b) {
  return a.filter(element => {
    return !b.includes(element);
  });
}

// 👇️ ['c', 'd']
console.log(getDifference(arr1, arr2));

我们传递给 Array.filter 方法的函数会被数组中的每个元素调用。

在每次迭代中,我们检查该元素是否不包含在另一个数组中。

filter 方法返回一个包含满足条件的元素的数组,换句话说,第一个数组中不包含在第二个数组中的元素。

但是 ,这不会返回数组之间的完整差异,因为我们只检查第一个数组中的元素是否不包含在第二个数组中。 我们没有检查第二个数组中的元素是否不包含在第一个数组中。

const arr1 = ['a', 'b'];
const arr2 = ['a', 'b', 'c', 'd'];

function getDifference(a, b) {
  return a.filter(element => {
    return !b.includes(element);
  });
}

// 👇️ []
console.log(getDifference(arr1, arr2));

这是相同的代码,但是我们交换了 arr1 和 arr2 变量的值。 现在 arr2 包含 4 个元素。

因为我们只迭代 arr1,它只有 2 个元素都包含在 arr2 中,所以该方法返回一个空数组。

我们本来期望 ['c', 'd'] 的返回值。

要解决这个问题,我们需要调用两次 getDifference 方法,然后合并结果。

const arr1 = ['a', 'b'];
const arr2 = ['a', 'b', 'c', 'd'];

function getDifference(a, b) {
  return a.filter(element => {
    return !b.includes(element);
  });
}

const difference = [
  ...getDifference(arr1, arr2),
  ...getDifference(arr2, arr1)
];

console.log(difference); // 👉️ ['c', 'd']

这是我们为使它正常工作所做的工作:

  1. 在第一个数组上调用 filter 方法,只返回第二个数组中不包含的元素。
  2. 在第二个数组上调用 filter 方法,只返回第一个数组中不包含的元素。
  3. 我们使用扩展运算符 (...) 语法将两个数组的结果合并到第三个数组中。

考虑展开运算符 ... 的一种简单方法是,我们将一个数组的值解包到另一个数组中。

现在我们的示例已经完成并返回两个数组之间的差异。

转载请发邮件至 1244347461@qq.com 进行申请,经作者同意之后,转载请以链接形式注明出处

本文地址:

相关文章

Do you understand JavaScript closures?

发布时间:2025/02/21 浏览次数:108 分类:JavaScript

The function of a closure can be inferred from its name, suggesting that it is related to the concept of scope. A closure itself is a core concept in JavaScript, and being a core concept, it is naturally also a difficult one.

Do you know about the hidden traps in variables in JavaScript?

发布时间:2025/02/21 浏览次数:178 分类:JavaScript

Whether you're just starting to learn JavaScript or have been using it for a long time, I believe you'll encounter some traps related to JavaScript variable scope. The goal is to identify these traps before you fall into them, in order to av

How much do you know about the Prototype Chain?

发布时间:2025/02/21 浏览次数:150 分类:JavaScript

The prototype chain can be considered one of the core features of JavaScript, and certainly one of its more challenging aspects. If you've learned other object-oriented programming languages, you may find it somewhat confusing when you start

扫一扫阅读全部技术教程

社交账号
  • https://www.github.com/onmpw
  • qq:1244347461

最新推荐

教程更新

热门标签

扫码一下
查看教程更方便