What is the _.intersection() method in Lodash?

Overview

The _.intersection() method in Lodash creates a new array from existing arrays by including only those values that are common in the given arrays.

Syntax

_.intersection([arrays])

Parameters

This method accepts the following parameters:

  • arrays: The arrays to be inspected.

Return value

This method returns an array in which only the common values of the given arrays are included.

Example

Let’s look at an example of the _.intersection() method in the code snippet below:

Console
Implementation of the _.intersection() method

Explanation

In the HTML tab:

  • Line 5: We import the lodash script.

In the JavaScript tab:

  • Lines 2 to 3: We create 2 arrays and populate them with a few values.
  • Line 6: We use the _.intersection() method to find the common values in both arrays.
  • Line 11: We print the output to the console.

Output

In the output, we see an array in which only the common values of both arrays are included.

Free Resources