Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

javascript

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; }); 
like image 258
Billy Blob Snortin Avatar asked Aug 27 '16 06:08

Billy Blob Snortin


People also ask

How do you break a reduced function?

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.

What is reduce () in JavaScript?

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 )

How does reduce work?

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.

How do you use reduce in JS?

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.


2 Answers

You can just return previousValue

[0, 1, 2, 3, 4].reduce(function(previousValue, currentValue, currentIndex, array) {   if(currentValue === "WHATEVER") {     return previousValue;   }   return previousValue + currentValue; }); 
like image 80
Jaromanda X Avatar answered Sep 25 '22 23:09

Jaromanda X


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; }); 
like image 31
Philzace Avatar answered Sep 22 '22 23:09

Philzace