Skip to main content

intersection

A function that returns a new array containing the values that exist in both arrays (the intersection).

By default, comparison is performed only for primitive values. If needed, the third argument iteratee function result can be used to determine intersecting elements.

This function removes duplicate values based on the first array.


Code​

🔗 View source code


Benchmark​

  • hz: Operations per second
  • mean: Average response time (ms)

Default​

NamehzmeanPerformance
modern-kit/intersection8,649,185.290.0001fastest
lodash/intersection3,722,050.210.0003slowest
  • modern-kit/intersection
    • 2.32x faster than lodash/intersection

with iteratee​

NamehzmeanPerformance
modern-kit/intersection10,210,296.980.0001fastest
lodash/intersectionBy1,278,057.730.0002slowest
  • modern-kit/intersection
    • 7.99x faster than lodash/intersectionBy

Interface​

typescript
function intersection<T, U>(
firstArr: T[] | readonly T[],
secondArr: T[] | readonly T[],
iteratee?: ((item: T) => U) | undefined
): T[];

Usage​

Basic Usage​

typescript
import { intersection } from '@modern-kit/utils';

intersection([1, 2, 3, 5, 7], [1, 2, 4, 5, 8]); // [1, 2, 5]

Iteratee Usage​

typescript
import { intersection } from '@modern-kit/utils';

const testArr1 = [
{ id: 1, name: 'john' },
{ id: 2, name: 'gromit' },
];

const testArr2 = [
{ id: 1, name: 'john' },
{ id: 3, name: 'dylan' },
];

intersection(testArr1, testArr2, (item) => item.id);
/*
[{ id: 1, name: 'John' }];
*/