Built-in Array Methods-map(), filter() and reduce()

·

5 min read

Introduction

An array in JavaScript is a type of global object used to store data between square brackets, separated by commas. It is a variable which can hold more than one value at a time. Arrays are zero-based, which means that they use numbered indices starting from 0 to access specific items.

Arrays allows us store multiple values in a single variable thereby making our code more readable, cleaner and maintainable. It is noteworthy to mention that an array can contain or hold any data type including multiple data type such as numbers, strings and objects.

At the beginning, we mentioned that arrays can be used to hold more than one value at a time. To demonstrate this, let us consider assigning the seven continents of the world to their own variables.

      //Assign the seven continents to seven variables
      let continent1 = "North-America";
      let continent2 = "South-America";
      let continent3 = "Asia";
      let continent4 = "Africa";
      let continent5 = "Europe";
      let continent6 = "Australia";
      let continent7 = "Antarctica"

See how we used the let keyword on each line to assign each continent to its variable? Pretty much stressful and repetitive right? One good thing is that we can correct repetition of these sorts by using arrays. In essence, we can simplify our data to make it simple, cleaner and more readable. Let me show you how:

      //Assign the seven continents
      let continents = [
            "North-America";
            "South-America";
            "Asia";
            "Africa";
             "Europe";
             "Australia";
             "Antarctica"
];

Instead of creating seven different variables just to house the different elements which is quite cumbersome, we can use a [ ] separated by commas as seen above.

Since arrays are zero-based, to access the first element, we append its index to the variable. Let me show you what I mean

      //console.log the first item of the continent array
        continent[0]
    //output
     North-America

Enough has been said about arrays. In this tutorial, we are going to cover some common built in array methods in JavaScript such as map(), filter() and reduce() in the simplest way possible. Now, lets get started.

map()

The map() method accepts a callback function which returns a new array as output while taking the currentValue, Index and the return array as argument without affecting the original array. For example, consider the following code:

const numbers = [10, 20, 30, 40, 50];
const newNumbers = numbers.map(function addNumber(digit, index) {
  return digit + index;
});

console.log(newNumbers); 
// Output: [10, 21, 32, 43, 54]

Let me make this simpler.

  • The callback function in this code is addNumber
  • The currentValue is each number in the iterated array (numbers), which is sent to addNumber in the parameter digit.
  • index simply receives the index of the current item in the iterated array that is being processed.
  • The final argument, array, is the array we are looping through, and is rarely used.

Futhermore, we could use the map() method to convert a string to an array using a special .call() method. Recall that everything in JavaScript is an object, and methods are functions attached to these objects. In this case, the .call() method allows you to use the context of one object on another. Here's an example:

const name = "Queen"
const map = Array.prototype.map

const newName = map.call(name, eachLetter => {
    return `${eachLetter}a`
})

console.log(newName)
//Expected output
   $ ["Qa", "ua", "ea", "ea", "na"]

This functions like the .split() method of a string, only that each individual string characters can be modified before being returned in an array.

filter()

The filter() method creates a new array by returning the values of the elements that pass a given condition. If the condition returns true, the given element(s) gets pushed to the new array and vice versa. Let's take a look at the example below:

const val= [3, 4, 7, 8, 9, 12, 15, 17, 18, 20, 25];
const odd= val.filter(numbers => numbers % 2 === 1);
console.log(odd);
//output
     3, 7, 9, 15, 17, 25

In the above, the condition numbers => numbers % 2 === 1 filtered the numbers in the variable val and passed the numbers that met the condition to a new const odd and as expected, the numbers that didn't meet the condition were not pushed to the new array.

Additionally, we could also use the filter() method on letters and strings. In the preceding example, I would show you how to use filter to return the number of vowels in an array. Let's begin:

const vowels= ['a', 'e', 'i', 'o', 'u'];
const countVowels = vowels.filter(vowels=>(/[aeiou]/gi).length;
console.log(countVowels);
//This should return
   5

filter() is an iteration method, and does not mutate the original array.

reduce()

The JavaScript reduce() method reduces an array to a single value. As with the filter() method, reduce() also iterates an array without disrupting or changing the values of the original array. It is commonly used with numbers such as finding the sum, multiplication, division etc of all the numbers in an array.

The Syntax for this array method is:

arr.reduce(callback[, initialValue])

Where the callback argument is a function that will be called once for every item in the array. Oftentimes, this function takes four arguments, but often only the first two are used.

Lets take a look at the example below:

let digits = [ 2, 10, 5, 7, 4, 8 ];

// Get the multiples of all numerical values
let multiple = digits.reduce((c, v) => {
    return c * v;
});

 multiple;
//output
22400

Conclusion

In this tutorial, we reviewed three major built-in iteration array methods in JavaScript with some examples. Iteration methods operate on every item in an array, and often perform a new function without changing the original array.

References

  1. Eloquent Javascript
  2. MDN Docs

Kindly leave a comment if you have any question or addition.

Thank you for reading :)