Understanding map() and filter() in Array in JavaScript

When you work with Arrays in JavaScript there are two methods that comes very very handy which are map() and filter().

When you work with Arrays in JavaScript there are two methods that come very very handy which are map() and filter(). Of course, other methods are also important, but these are the most frequently used.

map()

It is a method that act's on an Array and this method is going to have an anonymous function within it.

In this function, certain business logic is executed on each and every element of the Array, and the result of the function is stored as a result in another array (not the source array).

const a = [1, 2, 3]
const b = a.map(v => v*2) // [2,4,6]

Using map() on an Array in JavaScript

Check this 👇 to understand it even more better.

const users = [
  { firstName: "John", lastName: "Doe" },
  { firstName: "Jane", lastName: "Smith" }
];

const fullNames = users.map(user => `${user. firstName} ${user. lastName}`);
console.log(fullNames);

//Output: [ 'John Doe', 'Jane Smith' ]

filter()

This method is also like map() that act's on an Array, and this method is going to have an anonymous function within it.

Calling filter() on an array will create a new array and the filter() method will have a condition within it. Each element in the original Array is taken and a condition is performed on it. If the condition returns true, that element will be included in the resultant Array.

const a = [1, 2, 3, 4, 5, 6, 7]
const b = a.filter(v => v > 3)   //[4, 5, 6, 7]

Using filter() on an Array in JavaScript

Let's understand this also with an example!

const users = [
  { name: "Alice", age: 25 },
  { name: "Bob", age: 17 },
  { name: "Charlie", age: 30 }
];

const adults = users. filter(user => user.age >= 18);
console. log(adults);

//Output: [ { name: 'Alice', age: 25 }, { name: 'Charlie', age: 30 } ]

Along with this, there are a few more methods on Arrays that are also very frequently used, and we will talk about them in the next post.

Hope this is helpful!

Subscribe to Salesforce Casts

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
jamie@example.com
Subscribe