基于函数的数组对称差集

Beginner

This tutorial is from open-source community. Access the source code

简介

在本实验中,我们将探索如何使用 JavaScript 根据提供的函数找到两个数组之间的对称差集。我们将使用 Array.prototype.filter()Array.prototype.findIndex() 方法来比较两个数组的元素,并返回每个数组独有的值。在本实验结束时,你将更好地理解如何使用这些方法在 JavaScript 中比较和操作数组。

用于查找数组对称差集的函数

要使用提供的函数作为比较器来查找两个数组之间的对称差集,请执行以下步骤:

  1. 打开终端/SSH 并输入 node 以开始练习编码。
  2. 使用 Array.prototype.filter()Array.prototype.findIndex() 方法来找到合适的值。
  3. 使用给定的代码执行操作。
const symmetricDifferenceWith = (arr, val, comp) => [
  ...arr.filter((a) => val.findIndex((b) => comp(a, b)) === -1),
  ...val.filter((a) => arr.findIndex((b) => comp(a, b)) === -1)
];

例如,考虑以下输入:

symmetricDifferenceWith(
  [1, 1.2, 1.5, 3, 0],
  [1.9, 3, 0, 3.9],
  (a, b) => Math.round(a) === Math.round(b)
); // [1, 1.2, 3.9]

上述代码将返回 [1, 1.2, 3.9] 作为两个数组之间的对称差集。

总结

恭喜你!你已经完成了基于函数的数组对称差集实验。你可以在 LabEx 中练习更多实验来提升你的技能。