When using JavaScript's reduce, how do I skip an iteration?

You can just return previousValue

[0, 1, 2, 3, 4].reduce(function(previousValue, currentValue, currentIndex, array) {
  if(currentValue === "WHATEVER") {
    return previousValue;
  }
  return previousValue + currentValue;
});

You can simply use a ternary operator to pass the previous value if the condition is true ..or perform a certain action if false

[0, 1, 2, 3, 4].reduce((previousValue, currentValue, currentIndex, array)=>  {
  return(condition)?  previousValue : previousValue + currentValue;
});

Tags:

Javascript