JavaScript Array Methods for All
Its October and time for all things scary and Halloween related, however, you don’t need to be afraid of JavaScript array methods! Its my belief that everyone can understand almost anything… quantum physics and the supernatural aside, so long as the material is explained in a way that works for them. Our brains are all wired differently and we understand things in different ways. I hope this post can be that explanation for somebody.
I will cover four different methods: .map(), .filter(), .forEach(), and .reduce().
.map() is used in conjunction with arrays in order to apply the same passed function to each element in that array.
.map() takes the callback function as an argument and creates a NEW array. It also takes an optional starting index in case you don't want to start with 0.
This method can be used in place of a for loop.
Here are a few examples:
.forEach() is similar to .map(), it is also used to iterate through each array element, however it will NOT automatically return a new array with the updated values. You will instead need to push to a new array, or console log the updated values. .forEach() can also replace a for loop.
Here are a few examples:
.filter() is used to find a specific element or elements that match a certain parameter. It also creates a NEW array. It takes a callback function and an optional starting index. If nothing is found, an empty array will be returned. Here are some examples:
And finally .reduce(), also iterates through every element in an array and returns a single value. Each element is passed BACK into the function to compile the results. This is similar to summing an array with a for loop. .reduce() takes two arguments, the previous value, which is the value resulting from the previous function call, and the current value, which increases with each iteration. It also takes an optional starting index. You can also use it on an array of strings, however you would get the same result as using .join.
In each of these examples provided, I used arrow functions to apply each method, you can implement them a number of other ways like with a callback function, or an immediately invoked function.
Of course, there are many more array methods out there, check out this article https://www.freecodecamp.org/news/the-javascript-array-handbook/ from freeCodeCamp for a more extensive list.