You can use reduce:
const indexesOf = (arr, item) =>
arr.reduce(
(acc, v, i) => (v === item && acc.push(i), acc),
[]);
So:
const array = ["test234", "test9495", "test234", "test93992", "test234"];
console.log(indexesOf(array, "test234")); // [0, 2, 4]
An alternative approach could be having an iterator:
function* finder(array, item) {
let index = -1;
while ((index = array.indexOf(item, index + 1)) > -1) {
yield index;
}
return -1;
}
That's give you the flexibility to have the search in a lazy way, you can do it only when you need it:
let findTest234 = finder(array, "test234");
console.log(findTest234.next()) // {value: 0, done: false}
console.log(findTest234.next()) // {value: 2, done: false}
console.log(findTest234.next()) // {value: 4, done: false}
console.log(findTest234.next()) // {value: -1, done: true}
Of course, you can always use it in loops (since it's an iterator):
let indexes = finder(array, "test234");
for (let index of indexes) {
console.log(index);
}
And consume the iterator immediately to generate arrays:
let indexes = [...finder(array, "test234")];
console.log(indexes); // [0, 2, 4]
Hope it helps.
for
loop is the most efficient solution to the task. – Ivonneivor