Files
30-seconds-of-code/snippets/indexOfAll.md
Isabelle Viktoria Maciohsek 8bf67754ce Make expertise a field
2022-03-01 20:21:45 +02:00

533 B

title, tags, expertise, firstSeen, lastUpdated
title tags expertise firstSeen lastUpdated
Index of all matches array intermediate 2018-01-06T12:07:56+02:00 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); // []