761 B
761 B
title, tags, expertise, author, firstSeen, lastUpdated
| title | tags | expertise | author | firstSeen | lastUpdated |
|---|---|---|---|---|---|
| Check if all array elements are unique based on function | array | intermediate | maciv | 2020-10-19T22:15:05+03:00 | 2021-01-08T00:23:44+02:00 |
Checks if all elements in an array are unique, based on the provided mapping function.
- Use
Array.prototype.map()to applyfnto all elements inarr. - Create a new
Setfrom the mapped values to keep only unique occurrences. - Use
Array.prototype.lengthandSet.prototype.sizeto compare the length of the unique mapped values to the original array.
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