Filter() & Reduce()….when to use them.

Hello all ! I am still taking a slow walk through algorithms before understanding algos and really breaking down code, whenever I needed to iterate over an array or an object I usually went with a method that I’ve used before. Of course I learned about filter() and reduce() but I learned a whole bunch of other things too! I very quick realized I forgot a lot of the fundamentals of Javascript & working through algos understanding the fundamentals is key!

filter() :

The filter() method creates a new array of elements that pass the conditional provided. In other words, if the element passes and returns true, it will be included in the filtered array. And any element that fails or return false, it will be NOT be in the filtered array. It’s a good option when you want to receive only the information you need.

reduce():

The reduce method is used to reduce the elements of the array and combine them into a final array based on some reducer function that you pass. The reduce() method always takes in 2 parameters, an accumulator & current value. The accumulator parameter is where the code initializes from.

reduce() can make this much cleaner.
the acc parameter is the initializer

The screenshot below is a visual breakdown of what is actually happening in the code. In the first sumUp function the initializer was let sum = 0, the acc parameter is essentially doing the same thing but instead being initialized to 0, it’s initialized to the first element in the numArray which is 1.

Hope this helps! Happy coding!

The sassy developer