Monday, May 13, 2024
 Popular · Latest · Hot · Upcoming
51
rated 0 times [  54] [ 3]  / answers: 1 / hits: 113817  / 8 Years ago, tue, march 22, 2016, 12:00:00

How can I break the iteration of reduce() method?


for:


for (var i = Things.length - 1; i >= 0; i--) {
if(Things[i] <= 0){
break;
}
};

reduce()


Things.reduce(function(memo, current){
if(current <= 0){
//break ???
//return; <-- this will return undefined to memo, which is not what I want
}
}, 0)

More From » loops

 Answers
6

You CAN break on any iteration of a .reduce() invocation by mutating the 4th argument of the reduce function: "array". No need for a custom reduce function. See Docs for full list of .reduce() parameters.


Array.prototype.reduce((acc, curr, i, array))


The 4th argument is the array being iterated over.




const array = ['apple', '-pen', '-pineapple', '-pen'];
const x = array
.reduce((acc, curr, i, arr) => {
if(i === 2) arr.splice(1); // eject early
return acc += curr;
}, '');
console.log('x: ', x); // x: apple-pen-pineapple




WHY?:


The one and only reason I can think of to use this instead of the many other solutions presented is if you want to maintain a functional programming methodology to your algorithm, and you want the most declarative approach possible to accomplish that. If your entire goal is to literally REDUCE an array to an alternate non-falsey primitive (string, number, boolean, Symbol) then I would argue this IS in fact, the best approach.


WHY NOT?


There's a whole list of arguments to make for NOT mutating function parameters as it's a bad practice.




UPDATE


Some of the commentators make a good point that the original array is being mutated in order to break early inside the .reduce() logic.


Therefore, I've modified the answer slightly by adding a .slice(0) before calling a follow-on .reduce() step, yielding a copy of the original array.
NOTE: Similar ops that accomplish the same task are slice() (less explicit), and spread operator [...array] (slightly less performant). Bear in mind, all of these add an additional constant factor of linear time to the overall runtime ... + O(n).


The copy, serves to preserve the original array from the eventual mutation that causes ejection from iteration.




const array = ['apple', '-pen', '-pineapple', '-pen'];
const x = array
.slice(0) // create copy of array for iterating
.reduce((acc, curr, i, arr) => {
if (i === 2) arr.splice(1); // eject early by mutating iterated copy
return (acc += curr);
}, '');

console.log(x: , x, noriginal Arr: , array);
// x: apple-pen-pineapple
// original Arr: ['apple', '-pen', '-pineapple', '-pen']




[#62850] Saturday, March 19, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
byrondonavanc

Total Points: 675
Total Questions: 107
Total Answers: 105

Location: Peru
Member since Fri, Oct 14, 2022
2 Years ago
byrondonavanc questions
;