CyrefJS
CCyrefJS
فا
Back to documentation
Array/Since 1.38.0

intersection

Returns the elements from the first array that are also included in the second array.

intersection(array, values):T[]

Parameters

arrayT[]required

The first array whose elements are checked against the second array.

valuesT[]required

The array used to determine which elements from the first array should be included.

Returns

T[]

A new array containing elements from the first array that are also present in the second array.

Examples

01

Basic usage

Find the elements that exist in both arrays.

TypeScript
import { intersection } from "@cyref/js";

const array = [1, 2, 3, 4];
const values = [3, 4, 5, 6];

const result = intersection(array, values);

console.log(result);
// [3, 4]
02

With strings

The function also works with arrays of strings.

TypeScript
import { intersection } from "@cyref/js";

const array = ["javascript", "typescript", "python"];
const values = ["typescript", "python", "go"];

const result = intersection(array, values);

console.log(result);
// ["typescript", "python"]
03

No common elements

If the arrays have no matching elements, the function returns an empty array.

TypeScript
import { intersection } from "@cyref/js";

const array = [1, 2, 3];
const values = [4, 5, 6];

const result = intersection(array, values);

console.log(result);
// []
04

Duplicate elements

The function checks each element of the first array independently, so duplicate elements in the first array are preserved when they are included in the second array.

TypeScript
import { intersection } from "@cyref/js";

const array = [1, 2, 2, 3];
const values = [2, 3];

const result = intersection(array, values);

console.log(result);
// [2, 2, 3]
05

Empty arrays

An empty input array produces an empty result.

TypeScript
import { intersection } from "@cyref/js";

const result = intersection([], [1, 2, 3]);

console.log(result);
// []
Built with@cyref/js·Official documentation