VDL Plugin SDK

uniqBy

Import from @varavel/vdl-plugin-sdk/utils/arrays.

function uniqBy<T, U>(arr, mapper): T[];

Returns a new array containing only the unique elements from the original array, based on the values returned by the mapper function.

When duplicates are found, the first occurrence is kept and the rest are discarded.

Type Parameters

Type ParameterDescription
TThe type of elements in the array.
UThe type of mapped elements.

Parameters

ParameterTypeDescription
arrreadonly T[]The array to process.
mapper(item, index, array) => UThe function used to convert the array elements.

Returns

T[]

A new array containing only the unique elements from the original array, based on the values returned by the mapper function.

Examples

uniqBy([1.2, 1.5, 2.1, 3.2, 5.7, 5.3, 7.19], Math.floor);
// [1.2, 2.1, 3.2, 5.7, 7.19]
const array = [
  { category: 'fruit', name: 'apple' },
  { category: 'fruit', name: 'banana' },
  { category: 'vegetable', name: 'carrot' },
];
uniqBy(array, item => item.category).length
// 2