intersectionWith
arrays
This method is like intersection except that it accepts comparator which is invoked to compare elements of arrays.
Installation
Import
import { intersectionWith } from '@tulx/utils';Source Code
Implementation
/**
* This method is like intersection except that it accepts comparator which is invoked to compare elements of arrays.
*
* @param arrays - The arrays to inspect.
* @param comparator - The comparator invoked per element.
* @returns The new array of intersecting values.
*
* @example
* ```ts
* const objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }];
* const others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }];
* intersectionWith(objects, others, (a, b) => a.x === b.x && a.y === b.y);
* // [{ 'x': 1, 'y': 2 }]
* ```
*/
export function intersectionWith<T>(...args: readonly unknown[]): T[] {
if (args.length < 2) {
return [];
}
const comparator = args[args.length - 1] as (arrVal: T, othVal: T) => boolean;
const arrays = args.slice(0, -1) as readonly T[][];
if (arrays.length === 0) {
return [];
}
const firstArray = arrays[0];
const otherArrays = arrays.slice(1);
const result: T[] = [];
for (const value of firstArray) {
if (
otherArrays.some((arr) => arr.some((item) => comparator(value, item)))
) {
if (!result.some((item) => comparator(value, item))) {
result.push(value);
}
}
}
return result;
}
Example
import { intersectionWith } from '@tulx/utils';
const objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }];
const others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }];
intersectionWith(objects, others, (a, b) => a.x === b.x && a.y === b.y);
// [{ 'x': 1, 'y': 2 }]Related Functions
chunk
Creates an array of elements split into groups the length of size. If array can't be split evenly, the final chunk will be the remaining elements.
compact
Creates an array with all falsy values removed. The values false, null, 0, "", undefined, and NaN are falsy.
concat
Creates a new array concatenating array with any additional arrays and/or values.
difference
Creates an array of array values not included in the other given arrays. The order and references of result values are determined by the first array.
differenceBy
This method is like difference except that it accepts iteratee which is invoked for each element of array and values to generate the criterion by which they're compared.
differenceWith
This method is like difference except that it accepts comparator which is invoked to compare elements of array to values.