Jose Jose - 6 months ago 9
Javascript Question

Returning on conditional if from inside Array.filter

I'm trying to return the index of an item that meets a certain condition from within an

Array.filter
method, but I still keep getting an array of actual values instead of the indexes of the values I want.

Example:

var seq = [3, 4, 1, 2, 1];

seq.filter((curr, index) => {
if (seq[index + 1] < seq[index]) {
return index;
}
});

// returns [4, 2]
// want to return [1, 3] (the indexes of 4 & 2)


Is there a more efficient method I can use? I'm trying to avoid using a for loop. Thanks.

Answer

You can use reduce here

var seq = [3, 4, 1, 2, 1];

var result = seq.reduce((ar, curr, index) => {
  if (seq[index + 1] < seq[index]) ar.push(index);
  return ar;
}, []);

console.log(result)