Array Intersection Based on Function

JavaScriptJavaScriptBeginner
Practice Now

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

Introduction

In this lab, we will explore the concept of array intersection based on a provided comparator function in JavaScript. The purpose of this lab is to teach you how to use Array.prototype.filter() and Array.prototype.findIndex() to find intersecting values between two arrays. By the end of this lab, you will be able to apply this technique to your own projects and improve your programming skills in 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{{"`Array Intersection Based on Function`"}} javascript/data_types -.-> lab-28328{{"`Array Intersection Based on Function`"}} javascript/arith_ops -.-> lab-28328{{"`Array Intersection Based on Function`"}} javascript/comp_ops -.-> lab-28328{{"`Array Intersection Based on Function`"}} javascript/higher_funcs -.-> lab-28328{{"`Array Intersection Based on Function`"}} end

How to Find Array Intersection Based on Function using JavaScript

To find the elements that exist in both arrays based on a provided comparator function, follow these steps:

  1. Open the Terminal/SSH and type node to start practicing coding.

  2. Use Array.prototype.filter() and Array.prototype.findIndex() in combination with the provided comparator to determine intersecting values.

    const intersectionWith = (a, b, comp) =>
      a.filter((x) => b.findIndex((y) => comp(x, y)) !== -1);
  3. Call the intersectionWith() function with the two arrays and the comparator function as arguments.

    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]

This will return an array containing the intersecting values between the two arrays, based on the provided comparator function.

Summary

Congratulations! You have completed the Array Intersection Based on Function lab. You can practice more labs in LabEx to improve your skills.

Other JavaScript Tutorials you may like