-2

a = [-1, 150, 190, 170, -1, -1, 160, 180]

Given the above, how can I get another array of the indexes where -1 is found?

I was able to do it with a for loop and checking against the desired number, then getting the number of the iteration and pushing into an array. Wondering if there's a one liner or a way that won't involve a for loop.

uber
  • 4,163
  • 5
  • 26
  • 55

1 Answers1

1

You can use Array.prototype.reduce() to generate a new array of indices:

const a = [-1, 150, 190, 170, -1, -1, 160, 180];
console.log(a.reduce((acc, cv, idx) => {
    if (cv === -1) acc.push(idx);
    return acc;
}, []);
esqew
  • 42,425
  • 27
  • 92
  • 132