EasyCoders

Map, Filter, Reduce

Javascript arrays made easy

2019-04-18 Matthew BrimmerJavascript

I am always amazed when I see javascript developers not using Map, Filter, or Reduce when they should. So in this post I want to cover the how to use them and the benefits they are going to provide.

The most important thing to know about Map, Filter, and Reduce is they do not mutate the original array. They return a brand new array or in reduces case whatever type you reduce the array to. It is very common for bugs to be introduced by mutating an array in javascript. I avoid mutating arrays in javascript as much as I can by using methods that create new arrays. These practices have saved me a lot of time headache by not introducing hard to find bugs into my code. Let get started and take a look at these awesome array methods.

Map

Map returns a new array with each value returned from the function passed to map. As an example, if I had an array of numbers and I wanted to multiply each number by two. I can use map to do that like this:

const array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

const multipliedByTwo = array.map(number => number * 2)

console.log(multipliedByTwo)
// => [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]

console.log(array)
// => [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Notice that map calls the function we passed to it for each value in the array and returns the result to our brand new array. Keep in mind that we can pass any function we want to map. We can work with arrays of objects like this:

const array = [
  { name: 'John', age: 20 },
  { name: 'Jessica' age: 30 },
]

const sentences = array.map(object => `${object.name} is ${object.age}`)

console.log(sentences)
// => ['John is 20', 'Jessice is 30']

console.log(array)
// => const array = [
//      { name: 'John', age: 20 },
//      { name: 'Jessica' age: 30 },
//    ]

One last note on map, the function we pass can take two optional parameters that can be helpful. Map will pass the index of the current element in the array and the full array itself:

[1, 2, 3].map((currentNumber, index, array) => number)

Filter

Filter returns a new array with each element that passes the test of our function. I love this method for removing elements from an array without mutating the old array. This is how it works:

const array = ['filter', 'dont', 'filter', 'filter', 'dont']

const filtered = array.filter(string => string === 'filter')

console.log(filtered)
// => ['filter', 'filter', 'filter'']

console.log(array)
// => ['filter', 'dont', 'filter', 'filter', 'dont']

The function we pass needs to return true or false. Every element that we return true for will be in our new array and all false elements will not be. As with map we can test object, object properties, string, etc. Also like map filter will give our function access to the index or the array if needed.

Reduce

Reduce is the method I use the least, but is my favorite of the two and can be used to solve a number of problems in an elegant way. Reduce returns an accumulator by running our function with both the element and the accumlator. Reduce takes a second argument besides our function. The initial accumulator value. Lets have a look:

const array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

const sum = array.reduce((accumulator, number) => accumulator + number, 0)

console.log(sum)
// => 55

Notice we passed 0 after our function. We have to tell reduce what the default value of our accumulator needs to be. If we don’t an intial accumulator value it will use the first element in the array. So in the above example reduce would produced a value of 56 because the first call would have returned 1 + 1 instead of 0 + 1. Just like map and filter reduce will pass the index and array if needed

One of my favorites way to use reduce is to reduce arrays into objects. The next example is a popular code challenge given to developers Here it is:

const sentence = 'We can reduce arrays to objects if we want to'

const wordMap = sentence
  .toLowerCase()
  .split(' ') // split on spaces
  .reduce((accumulator, word) => {
    accumulator[word]
      ? accumulator[word] += 1
      : accumulator[word] = 1
  
    return accumulator
}, {})
// Must pass an empty object as the initial value

console.log(sentence)
// => 'We can reduce arrays to objects if we want to'
// Notice we didn't mutate the string.

console.log(wordMap)
// => {
//    we: 2,
//    can: 1,
//    reduce: 1,
//    arrays: 1,
//    to: 2,
//    objects: 1,
//    too: 1,
//    if:	1,
//    want: 1,
//  }

Word map solved.

Testing code with Map, Filter, and Reduce is usually easier since you don’t mutate the array. Pass it in and get the result out. Give these array methods a try and leave any question you have in the comments.

Happy Coding!

Loading...
EasyCoders - code made easy

Matthew Brimmer our lead instructor is a fullstack developer that has worked building large complex applictaions for a variety of companies in the Atlanta area. He currently works for RentPath on the Rent.com brand. He brings great experience and passion for helping others become successful software developers. Outside of development he enjoys kitesurfing, scuba diving and most other activities on the water.