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; });
The answer is you cannot break early from reduce , you'll have to find another way with builtin functions that exit early or create your own helper, or use lodash or something.
reduce() method in JavaScript is used to reduce the array to a single value and executes a provided function for each value of the array (from left-to-right) and the return value of the function is stored in an accumulator. Syntax: array.reduce( function(total, currentValue, currentIndex, arr), initialValue )
The reduce() method executes a user-supplied "reducer" callback function on each element of the array, in order, passing in the return value from the calculation on the preceding element. The final result of running the reducer across all elements of the array is a single value.
JavaScript Array reduce() The reduce() method executes a reducer function for array element. The reduce() method returns a single value: the function's accumulated result. The reduce() method does not execute the function for empty array elements. The reduce() method does not change the original array.
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; });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With