基于函数的数组交集

JavaScriptJavaScriptBeginner
立即练习

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

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

简介

在这个实验中,我们将基于 JavaScript 中提供的比较函数来探索数组交集的概念。本实验的目的是教你如何使用 Array.prototype.filter()Array.prototype.findIndex() 来找出两个数组之间的相交值。在本实验结束时,你将能够将此技术应用到自己的项目中,并提高你在 JavaScript 中的编程技能。


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/AdvancedConceptsGroup -.-> javascript/higher_funcs("Higher-Order Functions") subgraph Lab Skills javascript/variables -.-> lab-28328{{"基于函数的数组交集"}} javascript/data_types -.-> lab-28328{{"基于函数的数组交集"}} javascript/arith_ops -.-> lab-28328{{"基于函数的数组交集"}} javascript/comp_ops -.-> lab-28328{{"基于函数的数组交集"}} javascript/higher_funcs -.-> lab-28328{{"基于函数的数组交集"}} end

如何使用 JavaScript 根据函数查找数组交集

要根据提供的比较函数找出两个数组中都存在的元素,请按以下步骤操作:

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

  2. 结合使用 Array.prototype.filter()Array.prototype.findIndex() 以及提供的比较函数来确定相交值。

    const intersectionWith = (a, b, comp) =>
      a.filter((x) => b.findIndex((y) => comp(x, y)) !== -1);
  3. 将两个数组和比较函数作为参数调用 intersectionWith() 函数。

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

这将根据提供的比较函数返回一个包含两个数组中相交值的数组。

总结

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