The map() and filter() methods of Array in JavaScript

When we have an array of data, sometimes we try to just loop through all the data and print it to the UI, and sometimes we are required to filter the array of data before using it. We will discuss the two JavaScript array methods map() and filter() that can help to filter and modify the array data.

For looping through an array, we can use for loops but if we want to change or modify the existing array data and want a new array with the modified data, then we can use the map() method.

The map() method

The map() method loops through each element in an array and calls the provided function for each element. This method creates a new array and doesn’t alter the original array.

const numbers = [5, 6, 8, 14, 32];

const updatedNumbers = numbers.map((number) => {
    return number + 10;
});

console.log(updatedNumbers); // [15, 16, 18, 24, 42]

The provided function in map() takes 3 parameters.

  • Current element for which the function is got called (required)
  • Index of the element in the original array (optional)
  • Original array (optional)

Find duplicate elements in an array with the map() method

const numbers = [5, 6, 8, 5, 32, 14, 32];

const duplicates = [];

numbers.map((number, index, main) => {
     if (index !== main.indexOf(number)) duplicates.push(number);
});

console.log(duplicates); // [5, 32]

The filter() method

The filter() method creates a new array with the elements that satisfy the provided condition. This method calls a provided function for each element in the array and verifies the condition given in the provided function and passes only those elements that satisfy the given condition.

const numbers = [5, 6, 9, 32, 14];

const even = numbers.filter((number) => {
     return number % 2 === 0;
});

console.log(even); // [6, 32, 14]

The provided function in filter() method also takes 3 parameters.

  • Current element for which the function is got called (required)
  • Index of the element in the original array (optional)
  • Original array (optional)

Remove duplicate elements in an array

const numbers = [5, 6, 8, 5, 32, 14, 32];

const updated = numbers.filter((number, index, main) => {
     return index === main.indexOf(number);
});

console.log(updated); // [5, 6, 8, 32, 14]

Hope you have got a clear idea about both JavaScript array methods map() and filter(). Now you can use these methods to filter and modify data in arrays.

See Next

Leave a Reply

Your email address will not be published. Required fields are marked *