Reputation: 1201
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
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
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
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