Improve the array.forEach method with an optional predicate function parameter

This idea came when I was trying to implement a reusable code library. The method I called forWhich. So I thought, having it as an improvement on forEach would be better.

So here goes the definition:
forEach element in this array, execute this callback function, (optionally)provided it returns true for this predicate function

  • This eases the work of having to filter() an array for elements you don't want, before performing an action on all of them.
  • Also eases the work of, having to find() an element in an array before performing an action on it
  • It is a good refactoring code for these task.
  • It would be very useful in DOM manipulation, as the forEach method is used most in that case(I think).
  • More Importantly: It's not every case I would want to filter my array. I might want to manipulate one or some of the array elements.
  • Consider: Which one would be faster: having to filter an array first before executing callback or checking for condition on an array item before executing callback
  • There are a lot ways to solve a problem, but we aim for speed and less memory

Syntax:

array.forEach(callback, [predicate]);

Sample code:
Make each element's background blue provided it has the blue class. Although this is one that could be done easily in css with a class.

[DOMelem1, DOMelem2, ...]
.forEach((el) => {
// callback func
	makeBgBlue(el);
},
(el) => {
// predicate func
	return el.classlist.contains('make-blue');
});

Sample code 2:
Multiply each obj's x property by 2, provided its id property is equal to 'someId'

[obj1, obj2, ...]
.forEach((obj) => obj.x * 2, (obj) => obj.id === 'someId');

I don't know how this would be implemented, it may require a new Array method... As I know the TC39 wouldn't wanna break existing code, which in this case the thisArg parameter, which would normally be the second parameter to the function.

I was also thinking it could be implemented for the map array method also, but I haven't thought that through.

Thanks for considering this proposal.
JS :heart: - Kehinde Ogunrinola

I wonder why you are not just writing

array.filter(predicate).forEach(callback);

I'm not sure what you mean by

Ok. It's not every case you wanna filter your array is it? You might want to affect just some part of it.

filter doesn’t mutate, so you can ignore the returned array, and nothing will have been removed from the original.