824 B
824 B
title, tags, author, cover, firstSeen, lastUpdated
| title | tags | author | cover | firstSeen | lastUpdated |
|---|---|---|---|---|---|
| Check if array elements are equal based on function | array | maciv | blog_images/orange-coffee-2.jpg | 2020-10-19T22:14:49+03:00 | 2020-10-19T22:14:49+03:00 |
Checks if all elements in an array are equal, based on the provided mapping function.
- Apply
fnto the first element ofarr. - Use
Array.prototype.every()to check iffnreturns the same value for all elements in the array as it did for the first one. - Elements in the array are compared using the strict comparison operator, which does not account for
NaNself-inequality.
const allEqualBy = (arr, fn) => {
const eql = fn(arr[0]);
return arr.every(val => fn(val) === eql);
};
allEqualBy([1.1, 1.2, 1.3], Math.round); // true
allEqualBy([1.1, 1.3, 1.6], Math.round); // false