Exercise 12: Find All Indices of Element

Problem Statement

Create a function `indicesOf(arr, value)` that returns all indices of value in array. Example: indicesOf([1, 2, 3, 2, 4, 2], 2) → [1, 3, 5]

Sample Output:

indicesOf([1, 2, 3, 2, 4, 2], 2) => [1, 3, 5]
indicesOf([1, 1, 1], 1) => [0, 1, 2]

Solution

const indicesOf = (arr, value) => {
  const indices = [];
  arr.forEach((item, index) => { if (item === value) indices.push(index); });
  return indices;
};

Explanation

Overall Goal:

  • Array me value ke sabhi positions find karna.

Real world:

  • Search: multiple occurrences find.
  • Data analysis: pattern positions.