Files
30-seconds-of-code/snippets/indexOfAll.md
Robert Mennell a24423d5c6 indexOfAll.md returns a functions with shadow vars
It returned a function that accepted the same arguments again that when run again with the same inputs would eventually result
2018-08-02 12:57:02 -07:00

408 B

indexOfAll

Returns all indices of val in an array. If val never occurs, returns [].

Use Array.reduce() to loop over elements and store indices for matching elements. Return the array of indices.

const indexOfAll = (arr, val) =>
  arr.reduce((acc, el, i) => (el === val ? [...acc, i] : acc), []);
indexOfAll([1, 2, 3, 1, 2, 3], 1); // [0,3]
indexOfAll([1, 2, 3], 4); // []