Advanced Array Methods
Filter, Map and Reduce are 3 extremely powerful array methods that can take a lot of the burden off of loops in your code. They will also make your code cleaner and easier to read.
Filter
Let's say you have an array of items like above and you only want to keep the items with a number above 5. A for loop, if statement and .push() array method would reach that goal.
You would need to define a new array for the items to go, so that the original array stays intact. The for loop then iterates over the length of the array and pushes the index that matches the condition in the if statement into the new moreThan array.
The filter array method takes away a lot of the effort and leaves much cleaner code.
Filter takes in a callback function with three arguments.
- the current item,
- the current index - Optional,
- the array that filter was called on - Optional
For the majority of cases you will only ever take in the current item so for these examples I will exclude the latter two arguments. if you wish to read more about the other arguments, check out the MDN docs on the subject.
With the filter method, there is no need to define a new array as all the work is down by the filter method. There is also no need for the for loop and if statement as the filter method will visit each item and return a new array based on the retuned condition. With the filter method the return statement must be a boolean or else you will encounter problems with your code.
To make this code even cleaner we could also use an arrow function instead to provide an implicit return.
const moreThan = items.filter((item => item > 5));
Map
The map array method will loop over an array and produce a new array transformed by the callback function it takes in. Like the filter method it takes in three arguments
- the current item,
- the current index - Optional
- the array that map was called on - Optional
Again I will focus on just the current value but more information can be found here.
Like the filter method, map will loop through each item in the array and return a new array based on the condition give. Unlike filter this should not be a boolean.
The second example here shows how you can change the array from one of strings to one of numbers. Map has looped over the array here and returned the length of each word instead.
Notice how for the third example here I am using the same array as the second example. The original array never changes when you use these array methods, which is important for reuse-ability.
If you are not using arrow functions, you will need to include a return statement or else you will end up with an array filled with undefined.
Reduce
The reduce method works differently to the previous two methods, in that you're not limited to returning a new array. You can 'reduce' the array down to strings, numbers, objects etc...
The reduce method takes in a callback function that has 4 arguments. Unlike the map and filter methods, where only one argument was essential, two of these arguments are essential for reduce to work
- the previousValue - Also known as the accumulator
- the currentValue
- the current index - Optional
- the array that reduce was called on - Optional
As well as the callback function, the reduce method can also take in an optional value to indicate the initial value. This is because at the start of the array there is no previous value so it acts as the beginning of the loop. If this was not there, the callback function will take the first value of the array as the previous value, this value then acts as the start of the loop. This can lead to some issues, which I will explain. The best practice for the reduce method is to include an initial value.
The classic example for the reduce method is to add all the values in an array to 'reduce' it down to one total sum.
The initial value at the end (0) makes sure the total starts with 0. If it's removed the total will start with 12 and not include it in the final total. This will result in the same value at the end. Great!
However if we wanted to do something different with our reduce function, like add from a particular number, then the initial value has to be included to start the total in the correct position.
Say you wanted to subtract the array values from 100, you would need the initial value, otherwise you will start subtracting from 12 and return -26.
There is nothing stopping you from using reduce to combine words instead of numbers.
Finally, I will show one example where you could use all three of these functions at once using an array of objects.
First the shopping list is filtered, the condition looks at the price key in the objects and excludes everything that is not below 2.5. This is then mapped and only the price key is returned, this can then be reduced by adding the values and returning this number.
Conclusion
Top comments (2)
Nice Carl! I am going to include video of these if you don't mind. I just launched a youtube channel to hopefully help someone just like what you are doing.
Thanks for educating the community.
youtube.com/playlist?list=PLPo1hPb...
Nice one Carl! This concept confused me a lot too, but you've explained it really well, thank you :D