Billy Blob Snortin
Billy Blob Snortin

Reputation: 1201

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

I am trying to figure out a way to conditionally break out of an iteration when using JavaScript's reduce function.

Given the following code sums an array of integers and will return the number 10:

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

How can I do something like this:

[0, 1, 2, 3, 4].reduce(function(previousValue, currentValue, currentIndex, array) {
  if(currentValue === "WHATEVER") {
    // SKIP or NEXT -- don't include it in the sum
  }
  return previousValue + currentValue;
});

Upvotes: 55

Views: 34715

Answers (3)

Ali Mert Çakar
Ali Mert Çakar

Reputation: 326

Another way is to place an if statement, do your reducing logic there ignore other conditions. For example:

Instead of doing this:

let a = sorted.reduce((item,total)=>{
    if(total+item > k) return total;
ans++;
return total + item;
})

This works perfectly:

    let a = sorted.reduce((item,total)=>{
    if(total+item <= k) {
            ans++;
            return total + item;
    }
})

Upvotes: 2

Philzace
Philzace

Reputation: 266

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;
});

Upvotes: 4

Jaromanda X
Jaromanda X

Reputation: 1

You can just return previousValue

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

Upvotes: 101

Related Questions