What's the difference between .filter() and .map()?


#1

Question

What’s the difference between .filter() and .map()?

Answer

While both the .filter() and .map() methods will return a new array, .filter() will create a new array of array elements that pass a given test while .map() will create a new array made up of the results of calling a function on each array element.

.filter() example:

var arrOfNums = [2, 18, 42, 31, 17, 90, 5];

function isNumGreaterThanTwenty (num) {
  return num > 20; //returns a boolean, true when num is greater than 20, false when num is less than or equal to 20
}

var arrOfNumsGreaterThanTwenty = arrOfNums.filter(isNumGreaterThanTwenty); //the arrOfNumsGreaterThanTwenty variable is assigned a newly created array filled with the elements from arrOfNums that pass the test provided by isNumGreaterThanTwenty

console.log(arrOfNumsGreaterThanTwenty); //[42, 31, 90], our new array, is logged to the console

.map() example:

var arrOfNums = [2, 18, 42, 31, 17, 90, 5];

function addFive (num) {
  return num + 5; //returns whatever num is plus 5
}

var arrOfNumsPlusFive = arrOfNums.map(addFive); //assigns the arrOfNumsPlusFive variable to a new array of elements created by looping over arrOfNums and applying the addFive function on each element

console.log(arrOfNumsPlusFive); //[ 7, 23, 47, 36, 22, 95, 10 ] is logged to the console

#2

Extra Study

Given the expression patterns,

Array.filter(callback)
Array.map(callback)

note that the callback is not invoked, as in, callback()? Why is it written this way? We hand the function to the iterator by reference, only. The iterator has an internal variable that it will pass to the function on each element in the array.

We can emulate this by passing the whole function…

Array.filter(x => x > 20)
Array.map(x => x + 5)

Notice how the function is called on each element? By this time one will be well informed about arrow function syntax, so consider that we take full advantage of its short form. It’s actually useful to write code this way if the callback function can be reduced to this minimum (single line, implicit return, no braces or parens on formal parameter) since it doesn’t pollute the namespace with functions and takes less space in memory.

More complex code is preferably abstracted away to a local function, or if the same callback is used by multiple iterators or events. Then it is useful as it prevents repetition.

const greaterThanTwenty = x => x > 20;

const addFive = x => x + 5;

Botom line, simple one-offs do not need a dedicated callback function. Write it directly into the argument of the iterator (or event listener).