differenceBy
arrays
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.
Installation
Import
import { differenceBy } from '@tulx/utils';Source Code
Implementation
/**
* 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.
*
* @param array - The array to inspect.
* @param values - The values to exclude.
* @param iteratee - The iteratee invoked per element.
* @returns The new array of filtered values.
*
* @example
* ```ts
* differenceBy([2.1, 1.2], [2.3, 3.4], Math.floor); // [1.2]
* differenceBy([{ 'x': 2 }, { 'x': 1 }], [{ 'x': 1 }], 'x'); // [{ 'x': 2 }]
* ```
*/
export function differenceBy<T>(
array: readonly T[],
values: readonly T[],
iteratee: ((value: T) => unknown) | string
): T[] {
const getValue =
typeof iteratee === 'string'
? (item: T) => (item as Record<string, unknown>)[iteratee]
: iteratee;
const excludeSet = new Set(values.map((value) => getValue(value)));
return array.filter((item) => !excludeSet.has(getValue(item)));
}
Example
import { differenceBy } from '@tulx/utils';
differenceBy([2.1, 1.2], [2.3, 3.4], Math.floor); // [1.2]
differenceBy([{ 'x': 2 }, { 'x': 1 }], [{ 'x': 1 }], 'x'); // [{ 'x': 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.
differenceWith
This method is like difference except that it accepts comparator which is invoked to compare elements of array to values.
drop
Creates a slice of array with n elements dropped from the beginning.