Check if all array elements are unique based on function

Isabelle Viktoria Maciohsek · JavaScript, Array · Jan 7, 2021

Checks if all elements in an array are unique, based on the provided mapping function.

const allUniqueBy = (arr, fn) => arr.length === new Set(arr.map(fn)).size;
allUniqueBy([1.2, 2.4, 2.9], Math.round); // true
allUniqueBy([1.2, 2.3, 2.4], Math.round); // false

Recommended snippets