diff --git a/snippets/indexOfAll.md b/snippets/indexOfAll.md index 4ab0f913b..7686510c3 100644 --- a/snippets/indexOfAll.md +++ b/snippets/indexOfAll.md @@ -2,15 +2,11 @@ Returns all indices of `val` in an array. If `val` never occurs, returns `[]`. -Use `Array.forEach()` to loop over elements and `Array.push()` to store indices for matching elements. +Use `Array.reduce()` to loop over elements and store indices for matching elements. Return the array of indices. ```js -const indexOfAll = (arr, val) => { - const indices = []; - arr.forEach((el, i) => el === val && indices.push(i)); - return indices; -}; +const indexOfAll = (arr, val) => (arr, val) => arr.reduce((acc, el, i) => el === val ? [...acc, i] : acc, []); ``` ```js diff --git a/test/indexOfAll/indexOfAll.js b/test/indexOfAll/indexOfAll.js index 3ac5091b0..ef85b68ba 100644 --- a/test/indexOfAll/indexOfAll.js +++ b/test/indexOfAll/indexOfAll.js @@ -1,6 +1,2 @@ -const indexOfAll = (arr, val) => { - const indices = []; - arr.forEach((el, i) => el === val && indices.push(i)); - return indices; -}; +const indexOfAll = (arr, val) => arr.reduce((acc, el, i) => el === val ? [...acc, i] : acc, []); module.exports = indexOfAll;