Map() vs. filter()?

Hi all,

Just a short metaphysical question. What is the advantage of using filter() over map()? I have just started the iterators in the JS chapter and the way I see it, if we add a IF to a map() function, we can get the same result.

Is there something that I am severely missing here? Or it’s just for convenience, quicker and easier to use the filter() function?

Many thanks.

.map will return an array of same length. Even if you don’t return anything from the .map call-back method based on an if-statement it will populate the new array with some undefined elements. This is probably not what you want to do. Filter typically returns a shorter array with only the filtered results that we are looking for (as long as something is filtered out based on our call-back function).

2 Likes

map() maps. filter() filters. Can you open a can with a hammer and screwdriver? Sure. Is it merely for convenience that you would use a can opener? I suppose. Consider the following examples.

const a =[1, 2, 3, 4, 5, 6];

const oddNums = a.filter(n => n % 2 == 1);

console.log(oddNums); // [1, 3, 5]

const evenNums = a.map(n => n % 2 == 0);

console.log(evenNums); // [false, true, false, true, false, true]

const evenNums2 = [];

a.map(n => {
  if(n % 2 == 0) {
    evenNums2.push(n);
  }});
  
console.log(evenNums2); // [2, 4, 6]

The last use of map() to mimic the filter() method is returning an array, that array is simply lost since it doesn’t have a variable assigned to it. Kind of a wasted effort to unnecessarily create an array just to toss it away.

2 Likes