Lodash Intersection Mathematical Operation

In JavaScript development, utility libraries like Lodash provide specialized functions to manipulate collections and arrays efficiently. This article explains the exact mathematical operation performed by the Lodash _.intersection method, illustrating how it applies formal set theory to compute shared values across multiple arrays.

The _.intersection method in Lodash performs the mathematical operation known as Set Intersection, conventionally denoted by the symbol \(\cap\).

In classical set theory, the intersection of two sets, \(A\) and \(B\) (written as \(A \cap B\)), represents the set containing all distinct elements that belong simultaneously to both \(A\) and \(B\). Formally, this is defined as:

\[A \cap B = \{ x : x \in A \text{ and } x \in B \}\]

When applied to more than two sets (\(A \cap B \cap C \dots\)), the operation yields only the elements that are common to every single participating set.

Lodash mirrors this mathematical principle directly on JavaScript arrays. The method accepts multiple arrays as arguments and returns a new array containing only the values that appear in all provided arrays.

const _ = require('lodash');

const array1 = [2, 1, 2];
const array2 = [2, 3];

const result = _.intersection(array1, array2);
// result => [2]

Key characteristics of this operation in Lodash include: