Files
30-seconds-of-code/snippets/index-of-all.md
2023-04-28 22:29:23 +03:00

512 B

title, type, tags, cover, dateModified
title type tags cover dateModified
Index of all matches snippet
array
jars-on-shelf-2 2020-10-22T20:23:47+03:00

Finds all indexes of val in an array. If val never occurs, returns an empty array.

  • Use Array.prototype.reduce() to loop over elements and store indexes for matching elements.
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); // []