JavaScript filter() Function | Array.prototype.filter()

Themomsco [CPS] IN

If you don’t know about JavaScript filter() function then this tutorial is for you. In this tutorial, we will understand the uses of filter function in JavaScript.

If you know the uses of JavaScript map() function, it means you know the filter() function. Both are pretty similar, The filter() function receives the same argument as the map() function.

The difference is only that the callback returns either true or false. If the callback returns true, the array keeps the element or element filtered out if the callback returns false.

JavaScript filter() Definition

JavaScript filter() function returns a new array created from all elements of an array and each element pass the test performed on the original array.

Now, Let’s understand the syntax and we’ll also see some example around it.

filter() Method Syntax

var newArray = mainArray.filter(function(element) {
  return condition;
});

filter() Method Example

Let’s say we have an array of numbers and our task is to filter out all the even numbers from it.

You can achieve this using the filter method easily.

var numbersArray = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15];

var evenNumbers = numbersArray.filter(function (num) {
  return num % 2 === 0;
})
console.log(evenNumbers); // Output is [2, 4, 6, 8, 10, 12, 14]

You can make it for readable using ES6 syntax. But for this, you should have Babel or TypeScript.

const numbersArray = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15];

const evenNumbers = numbersArray.filter( num => {
  return num % 2 === 0;
});
console.log(evenNumbers); // Output is [2, 4, 6, 8, 10, 12, 14]

 

 

 

 

Themomsco [CPS] IN

Leave a Reply