Hacker News new | ask | show | jobs
by dragonwriter 1583 days ago
> ok, how do you implement a break of the iteration in map in JavaScript?

If you want something that behaves like:

  array.map(x => {
    if (x > 2) { break; } // can't really use break here!
    else { return x; }
  });
you do this:

  [...array].map((x,i,a) => {
    if (x > 2) { a.splice(i); }
    else { return x; }
  });
(if you don’t need the array later, you can just use “array” instead of [...array]; the latter is just used because the break effect is achieved by mutating the array to delete all the elements subsequent to the one you are working, terminating the iteration, and copying the array initially means you don’t stomp the original.)
1 comments

huh, that's actually interesting and horrifying I guess, I knew the third argument of map was the original array but I had never seen a usage of it - I guess mutating an array while working on it goes against instinct for just about everyone.

so I guess I was wrong, you can get the same functionality of break in map, albeit in a way that, right at this moment, makes me uneasy.