Can we use map function instead of filter function?

Can we use map function instead of filter function?
0

#1

Would i get same result with map if i use conditional statements instead of filter function which filters based on condition being true or false


#2

.map would give you the same number of elements as the original array. .filter would give you (usually) an array with fewer elements.

It really depends on what you want to achieve. If you want to transform the elements of your array, you’d use .map. If you want to get the elements of your array that satisfy some criteria, you’d use .filter.


#3

If your goal is to “take out” elements from an array… using map is not really a good idea.

The reason is that map requires you to always have a return otherwise it will return undefined by default.
Let’s look it with an example:

const filter = (arr) => {
   let f = arr.filter((n) =>  n < 4 );
  return f;
}

const map = (arr) => {
  let m = arr.map((n) => {
    
    if (n < 4) {
      return n;
    }
    
  });
  return m
}

const data = [1,2,3,4,5,6,7,8,9];
filter(data);
map(data);

The first example, filter will return [1,2,3] as expected since we asked to return only values that are lower than 4 here:

  • arr.filter((n) => n < 4 );

However in the map example we are asking the same thing: if the number is less than 4, return it

let m = arr.map((n) => {
    
    if (n < 4) {
      return n;
    }
    
  });

But since we have not specified anything to do on all the other cases this is the returned array:
[ 1, 2, 3, undefined, undefined, undefined, undefined, undefined, undefined]

In short:
map will transform every element of the array
filter take out element that don’t belong there.


#6

You can use reduce. If minute performance gains are your bag, then it will be faster. If not, the main benefit is you can replace a function that maps and then filters with just reduce.