Rewrite Your Own Array Methods: forEach, map, filter, find, and reduce
So, I decided to rewrite these functions in the hope that it will help them get a better understanding of these methods.
To use array methods, you can have a look at a previous piece I wrote.
arr.forEach method allows you to run a function for every element of the array.
forEach doesn’t return anything.
Rewrite for use with the
Test it on the Chrome console:
See, the result is exactly the same.
So, basically, the
forEach function implements a
for loop inside it.
We can also make
myForeach better by adding it in the array prototype chain and use it as a normal
Done! And, we can use something like this
With the same approach, we can rewrite
map find filter reduce with a
map function always returns the new array with the same length as the original.
find function returns the first item that matches the callback function, or
undefined if there is nothing that matches.
This works like the
find function, but instead of returning the first matched item,
filter will return the array of matched items or an empty array if nothing matched.
Instead of returning an array, such as
reduce returns any value we want. We only need to pass the initial value, then modify it over each iterator.
for loop for better understanding how it works under the hood.
.sort function is not mentioned in this article because it deserves its own post which I will try to write soon.
Thanks for reading.