From 5a1f608589be4df76da1199b252ea0bc7229f2ed Mon Sep 17 00:00:00 2001 From: Isabelle Viktoria Maciohsek Date: Mon, 19 Oct 2020 22:14:49 +0300 Subject: [PATCH] Add allEqualBy --- snippets/allEqualBy.md | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 snippets/allEqualBy.md diff --git a/snippets/allEqualBy.md b/snippets/allEqualBy.md new file mode 100644 index 000000000..204ea01cb --- /dev/null +++ b/snippets/allEqualBy.md @@ -0,0 +1,22 @@ +--- +title: allEqualBy +tags: array,intermediate +--- + +Checks if all elements in an array are equal, based on the provided mapping function. + +- Apply `fn` to the first element of `arr`. +- Use `Array.prototype.every()` to check if `fn` returns 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 `NaN` self-inequality. + +```js +const allEqualBy = (arr, fn) => { + const eql = fn(arr[0]); + return arr.every(val => fn(val) === eql); +}; +``` + +```js +allEqualBy([1.1, 1.2, 1.3], Math.round); // true +allEqualBy([1.1, 1.3, 1.6], Math.round); // false +```