๐ŸŸก JS: forEach, map, reduce, filter & sort overview ๐ŸŸก

Thread By @MrConerMurphy

27/02/2021 16:09

9 Tweets


๐ŸŸก 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

#100DaysOfCode #developer #JavaScript

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



1๏ธโƒฃ .forEach()

.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

2๏ธโƒฃ .map()

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

3๏ธโƒฃ .reduce()

.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

4๏ธโƒฃ .filter()

.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

5๏ธโƒฃ .sort()

.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