JavaScript by Patrik

Filter Out The Values You Want to Skip

Instead of thinking about how to break out of a forEach(), try thinking about how to filter out all the values you don't want forEach() to iterate over. This approach is more in line with functional programming principles.

The findIndex() function takes a callback and returns the first index of the array whose value the callback returns truthy for. Then the slice() function copies part of the array.

// Prints "1, 2, 3"
const arr = [1, 2, 3, 4, 5];

// Instead of trying to `break`, slice out the part of the array that `break`
// would ignore.
arr.slice(0, arr.findIndex(v => v > 3)).forEach(v => {
  console.log(v);
});

Comments

Leave a Comment

All fields are required. Your email address will not be published.