🟡 JS: forEach, map, reduce, filter & sort overview 🟡
These 5 functions have become a staple of working with arrays in JS since they were introduced. Here's a quick overview of what each one does and how we can use them. 🧵 1/9
Before diving into the list, I wanted to cover what allows all of these functions to exist. They are all examples of 'Higher-Order Functions'.
This is when a function operates on another. I covered it further in the thread linked. 2/9
.forEach() allows us to loop over an array and access each item individually, similar to how a for loop would do it but in a nicer syntax.
❗ You can't return values from a .forEach() if you want to return values you need to use .map(). 3/9
As mentioned for .forEach(), if you want to iterate over an array, manipulate the value(s) in some way & return the final results, you need to use a .map()
.map() and .forEach() are very similar, to tell which to use think if you need to return a new array. 4/9
.reduce() is a special method that is often one of the hardest to learn due to how versatile it is.
With a .map() you operate on the values & return. But, with .reduce(), you can do pretty much anything.
In this example, I sum the values in the array. 5/9
.filter() does what it says on the tin, it filters the array down to a smaller size based on if each value passes/fails the filter condition.
In this example, I check if the value is an even number by checking if the remainder of dividing by 2 is 0. 6/9
.sort() allows us to sort an array based on a compare function we pass in.
Sort works by taking 2 values (a,b) and checking if one is larger than the other to ascertain the correct order. This is then returned as a new array. 7/9
❓ Got any questions ❓
If you have any questions or want more info on any of these methods let me know ⏬ 8/9
This is thread 27/28 in my February Twitter Thread Challenge. 📆
If you're interested in following along in my challenge or like this thread's content and want to see more please consider retweeting it for others to see and following me for future threads. 😀 9/9