How to early break reduce() method?

You can use functions like some and every as long as you don't care about the return value. every breaks when the callback returns false, some when it returns true:

things.every(function(v, i, o) {
  // do stuff 
  if (timeToBreak) {
    return false;
  } else {
    return true;
  }
}, thisArg);

Edit

A couple of comments that "this doesn't do what reduce does", which is true, but it can. Here's an example of using every in a similar manner to reduce that returns as soon as the break condition is reached.

// Soruce data
let data = [0,1,2,3,4,5,6,7,8];

// Multiple values up to 5 by 6, 
// create a new array and stop processing once 
// 5 is reached

let result = [];

data.every(a => a < 5? result.push(a*6) : false);

console.log(result);

This works because the return value from push is the length of the result array after the new element has been pushed, which will always be 1 or greater (hence true), otherwise it returns false and the loop stops.


There is no way, of course, to get the built-in version of reduce to exit prematurely.

But you can write your own version of reduce which uses a special token to identify when the loop should be broken.

var EXIT_REDUCE = {};

function reduce(a, f, result) {
  for (let i = 0; i < a.length; i++) {
    let val = f(result, a[i], i, a);
    if (val === EXIT_REDUCE) break;
    result = val;
  }
  return result;
}

Use it like this, to sum an array but exit when you hit 99:

reduce([1, 2, 99, 3], (a, b) => b === 99 ? EXIT_REDUCE : a + b, 0);

> 3

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 + 1*(O(1)).

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']

OLD

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.


Don't use reduce. Just iterate on the array with normal iterators (for, etc) and break out when your condition is met.