loading...
Cover image for Understanding Array Higher-Order Functions

Understanding Array Higher-Order Functions

jessicaiwu profile image Jessica Iwu ・3 min read

Having an understanding of how Array Higher-Order functions work can make complex looping operations in JavaScript very seamless.

The higher-order functions to be discussed in this article are : forEach(), map(), filter(), and reduce().

At the end of this article, you'll understand what each function represents, and how to apply them in problem-solving.

Array.forEach()

Running the .forEach() method on an array executes a callback function for each element that exists in that array.

The callback function is the block that specifies what operation is to be carried out.

In the snippet below, the .forEach() method iterates over every friend element in the friends array, and logs each string to the console dynamically using the ${friend} template literal.


    const friends = ['Chief', 'Somto', 'Elma', 'Zee'];
    friends.forEach(friend => {
      console.log (`I love working with ${friend}`);
    });

    // I love working with Chief
    // I love working with Somto
    // I love working with Elma
    // I love working with Zee

Array.map()

The .map() method is similar to the .forEach() method except that it produces a new array.

Map Illustration

With the .map() method, you can create a new array by manipulating each element in the existing array. In the illustration above, the original array contains [2,3,4], and by mapping, the new array contains the square of the original array; [4,9,16].


const ingredients = ['Jam', 'oat', 'lemon', 'lettuce', 'oil', 'fish'];

const newMeal = ingredients.map(ingredient => {
  return ingredient[0];
});

console.log(newMeal); // ['J', 'o', 'l', 'l', 'o', 'f']
console.log(newMeal.join(' ')); //Jollof

In the snippet above, there’s an ingredients array that is mapped to create a newMeal array by returning the first character of each ingredient. Notice that by attaching .join(' ') to the newMeal array, the array strings become one single string.

Array.filter()

The .filter() method shares similar characteristics with the .map() method because it returns a new array. However, just like the name implies, it filters the elements in the array based on any conditions provided.

filtering strings


const stack = ['desk', 17, 'chair', 5, 'sofa'];
const newStack = stack.filter(item => {
    return typeof(item) === 'string'; 
});

console.log(newStack); //['desk', 'chair', 'sofa']

filtering numbers


const stack = ['desk', 17, 'chair', 5, 'sofa'];
const newStack = stack.filter(item => {
    return typeof(item) === 'number'; 
});
console.log(newStack); //[17, 5]

Array.reduce()

The .reduce() method iterates an array and returns a single value. This value could be any data structure - number, string, array, etc.

The callback function passed to the reduce method accepts accumulator and currentValue as parameters and returns a single value.

Using the reduce method in the code snippet below, we are able to loop through the objects in the socialMedia array in order to get the values of the name property.

Note: When using the reduce method on an object array, a second parameter (like the empty array in the snippet) should be added.


const socialMedia = [
  {name: 'Instagram', url:'jessontel.com'},
  {name: 'twitter', url:'abc.com'}
];

const mediaName = socialMedia.reduce((accumulator,currentValue) => {
  accumulator.push(currentValue.name);
  return accumulator
}, []);

console.log(mediaName); //[ 'Instagram', 'twitter' ]


Another quick reduce example


const expenseList = [1000, 50, 250, 999];
const expenseSum = expenseList.reduce((accumulator, currentValue) => {
  return accumulator + currentValue;
, 0}
);
console.log(expenseSum); // 2,299

In the reduce method example above, the expenseList array is reduced to the expenseSum value 2,999.

The first element in the array is the default accumulator value, and the second element is the current value.

Conclusion

Iterators are very useful methods, not just in JavaScript but in programming generally. Each of them solves specific problems and make array manipulations an easy feat.

Thanks for reading! πŸ‘‹πŸ½

If you found this article useful, please let me know and share it too so that others could benefit.
To connect with me, kindly follow me on twitter.

Discussion

pic
Editor guide
Collapse
tobiobeck profile image
Tobi Obeck

forEach(), map(), filter(), and reduce() are usually called higher-order functions, not iterators.

Iterators and Generators are their own concept in JS:
developer.mozilla.org/en-US/docs/W...

Collapse
jessicaiwu profile image
Collapse
xoeseko profile image
Xoeseko

The jollof was a nice touch πŸ˜‚πŸ‘ŒπŸΎ