基于函数的数组中的唯一值

Beginner

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

简介

在本实验中,我们将探索一个 JavaScript 函数,该函数基于提供的比较函数来帮助找出数组中所有唯一值。我们将使用 Array.prototype.reduce()Array.prototype.some() 方法来创建一个新数组,该数组仅包含基于提供的比较函数的每个值的首次唯一出现。本实验将帮助你更深入地理解如何在 JavaScript 中操作数组。

使用函数查找数组中的唯一值

要查找数组中的所有唯一值,请提供一个比较函数。

使用 Array.prototype.reduce()Array.prototype.some() 来创建一个只包含每个值首次唯一出现的数组。比较函数 fn 接受两个参数,即正在比较的两个元素的值。

const uniqueElementsBy = (arr, fn) =>
  arr.reduce((acc, v) => {
    if (!acc.some((x) => fn(v, x))) acc.push(v);
    return acc;
  }, []);

要测试该函数,请使用以下示例:

uniqueElementsBy(
  [
    { id: 0, value: "a" },
    { id: 1, value: "b" },
    { id: 2, value: "c" },
    { id: 1, value: "d" },
    { id: 0, value: "e" }
  ],
  (a, b) => a.id == b.id
); // [ { id: 0, value: 'a' }, { id: 1, value: 'b' }, { id: 2, value: 'c' } ]

通过打开终端/SSH 并输入 node 开始练习编码。

总结

恭喜你!你已经完成了“基于函数的数组中的唯一值”实验。你可以在 LabEx 中练习更多实验来提升你的技能。