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

JavaScriptJavaScriptBeginner
立即练习

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

💡 本教程由 AI 辅助翻译自英文原版。如需查看原文,您可以 切换至英文原版

简介

在本实验中,我们将学习如何在 JavaScript 中基于比较函数创建一个过滤掉重复值的数组。我们将使用 Array.prototype.filter()Array.prototype.every() 方法来创建一个只包含非重复值的数组。本实验将提供使用比较函数过滤数组中重复值的实践经验。


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL javascript(("`JavaScript`")) -.-> javascript/BasicConceptsGroup(["`Basic Concepts`"]) javascript(("`JavaScript`")) -.-> javascript/AdvancedConceptsGroup(["`Advanced Concepts`"]) javascript/BasicConceptsGroup -.-> javascript/variables("`Variables`") javascript/BasicConceptsGroup -.-> javascript/data_types("`Data Types`") javascript/BasicConceptsGroup -.-> javascript/arith_ops("`Arithmetic Operators`") javascript/BasicConceptsGroup -.-> javascript/comp_ops("`Comparison Operators`") javascript/BasicConceptsGroup -.-> javascript/obj_manip("`Object Manipulation`") javascript/AdvancedConceptsGroup -.-> javascript/higher_funcs("`Higher-Order Functions`") subgraph Lab Skills javascript/variables -.-> lab-28336{{"`基于函数过滤数组中的唯一值`"}} javascript/data_types -.-> lab-28336{{"`基于函数过滤数组中的唯一值`"}} javascript/arith_ops -.-> lab-28336{{"`基于函数过滤数组中的唯一值`"}} javascript/comp_ops -.-> lab-28336{{"`基于函数过滤数组中的唯一值`"}} javascript/obj_manip -.-> lab-28336{{"`基于函数过滤数组中的唯一值`"}} javascript/higher_funcs -.-> lab-28336{{"`基于函数过滤数组中的唯一值`"}} end

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

以下是如何通过基于比较函数 fn 过滤掉唯一值来创建一个只包含非唯一值的数组:

const filterUniqueBy = (arr, fn) =>
  arr.filter((v, i) => arr.some((x, j) => (i !== j) === fn(v, x, i, j)));

要使用此函数,请使用两个参数调用 filterUniqueBy():要过滤的数组和比较函数。比较函数应接受四个参数:正在比较的两个元素的值及其索引。

例如,如果你有一个对象数组,并且想要过滤掉具有唯一 id 值的对象,可以这样做:

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

要开始练习编码,请打开终端/SSH 并输入 node

总结

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

您可能感兴趣的其他 JavaScript 教程