Photo by Cristina Gottardi on Unsplash
Javascript Array Methods: Foreach, Map, Filter
Back to Basics: Javascript
Hi Everyone,
My friend is starting to learn how to code, and this week I worked with him on some Javascript higher order functions for arrays. Which made me want to share with those also learning.
Let's get started!
ForEach
The forEach
array method is used to iterate over every element in an array. Instead of having to write a for
loop for example, you can simply use dot notation and call forEach
.
In the example below, we have an array of menu items and want to log them out. Typically, we would write a for
loop to iterate over every element. But, as we can see the higher order forEach
function allows us to do this in a much more concise way.
const menuItems = [
{ name: 'hamburger', type: 'entree' },
{ name: 'fries', type: 'side' },
{ name: 'soda', type: 'drink' }
];
menuItems.forEach((item) => {
console.log(item)
});
/* result =
{ name: 'hamburger', type: 'entree' },
{ name: 'fries', type: 'side' },
{ name: 'soda', type: 'drink' } */
Map
The map
array method on the other hand iterates and executes a provided function on every element in an array. The difference is the result of the method is an array.
Again in the example below, we have our array of menu items. This time we want an array of just the item names. As we can see, we can produce an array of menu item names by simply returning each each item's name. This is useful when you need to create a new modified array from another, without having to write the additional code needed in a typical for
loop.
const menuItems = [
{ name: 'hotdog', type: 'entree' },
{ name: 'hamburger', type: 'entree' },
{ name: 'fries', type: 'side' },
{ name: 'onion rings', type: 'side' },
{ name: 'milkshake', type: 'drink' },
{ name: 'soda', type: 'drink' }
];
const result = menuItems.map((item) => {
return item.name
});
/* result = [ 'hotdog', 'hamburger', 'fries',
'onion rings', 'milkshake', 'soda' ] */
Filter
The filter
method is similar to the map
array method. It executes a filter on the array and returns every element which passes the filter.
In our menu item example, we want to get all of the entrees on the menu. We can do this by passing the filter item.type === 'entree'
into the filter
array method. This results in an array of only entree items.
const menuItems = [
{ name: 'hotdog', type: 'entree' },
{ name: 'hamburger', type: 'entree' },
{ name: 'fries', type: 'side' },
{ name: 'onion rings', type: 'side' },
{ name: 'milkshake', type: 'drink' },
{ name: 'soda', type: 'drink' }
];
const result = menuItems.filter((item) => {
return item.type == 'entree'
});
/* result =
[ { name: 'hotdog', type: 'entree' },
{ name: 'hamburger', type: 'entree' } ]
*/
Conclusion
In conclusion, we can see that we can use higher order array functions to streamline our code, making it easier to read, and maintain. I use these methods almost daily, and now you can too!
Til next time - happy coding!