how to use javascript array filter method?

In this article, let’s discuss the usage of the javascript array filter method.

The¬†filter()¬†method creates a new array with all elements that pass the test implemented by the defined function. Array filter method does not execute the function for the empty array and also it doesn’t make any changes to the original array as well.

Syntax

var filteredArray = arr.filter(callback(element[, index[, array]])[, thisArg])
  • element – The current element being processed in the array.
  • index – Optional. The index of the current element being processed in the array.
  • array – Optional. The array, filter called upon.

Example

var ages = [30, 20, 5, 60];

function checkMajorAdults(age) {

  return age >= 18;

}

function myFunction() {

  console.log(ages.filter(checkMajorAdults)); // outputs [30, 20, 60]

}

Example 2:

var wordsArray= ['one', 'two', 'three', 'four', 'five', 'fiftysix'];

const result = wordsArray.filter(wordsArray => wordsArray.length > 4);

console.log(result); // expected output: Array ["three", "fiftysix"]

This is the syntax and usage of the javascript array filter method.

See also:

javascript reduce method

Javascript remove element from array

Thanks for reading this tutorial. If you have any questions or improvements with respect to this tutorial, Please feel free the comment below or send me an email at [email protected]

Summary
 how to use javascript array filter method
Article Name
how to use javascript array filter method
Description
This article explains how to use javascript array filter method which creates a new array with elements passed the test function with examples.
Author
Publisher Name
askvikram.com
Publisher Logo

Leave a Comment