Files
30-seconds-of-code/snippets/indexOfAll.md
Angelos Chalaris b5c5a0d174 Update indexOfAll.md
2020-02-18 20:24:26 +02:00

453 B

title, tags
title tags
indexOfAll array,intermediate

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

Use Array.prototype.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); // []