Using Array Filter In JavaScript to Filter Array Elements

When you see multiple options available while online shopping, and you want to narrow down the search results; what do you do? Filter out the options, right? This is precisely what the array filter in JavaScript enables a programmer to do. As the name suggests, the filter method will filter out the elements of an array based on the specified test condition. It will iterate through all the elements and imply the test condition on them. It will then return a new array of elements that will pass the condition.

Learn the Ins & Outs of Software Development

Caltech Coding BootcampExplore Program
Learn the Ins & Outs of Software Development

Syntax and Parameter Values of JavaScript Array Filter()

The syntax of array filter in JavaScript is:

array.filter(callbackFn(item, index, array), thisArg)

In the above syntax:

  • CallbackFn: This is a required parameter that holds the callback function that is supposed to be implemented on each element.
  • Item: It is a required parameter that holds the current element that is being processed.
  • Index: This is an optional parameter holding the index value of the element being processed with the index starting from 0.
  • Array: It is an optional parameter that holds the original array on which the filter method is called.
  • ThisArg: This is an optional parameter that, when passed, will hold the “this” value for each invocation. If the argument is not given, undefined will be used as the default value for this keyword.

Return value: The JavaScript array filter method returns a new method with only the elements that have passed the test condition.

How JavaScript Array Filter() Works?

Consider the example given below to understand how array filter in JavaScript works. In this example, we will create an array with integer values. Next, we will use the array filter() method to filter out the even numbers and log the resultant array to the console.

let num = [3, 6, 7, 12, 18, 23, 44, 62, 81];

let even_num = num.filter(function(item){

  return item % 2 == 0; });

console.log(even_num);

Output:

Array_Filter_in_JavaScript_1

As you can see in the output, the array filter method added only the even elements of the num array to the new even_num array. Now, let’s understand how this works step by step.

  1. The filter method is declared with the test condition return item % 2 == 0
  2. It will start iterating through the elements of the num array and pass the test condition
  3. If the remainder of the item divided by 2 is 0, it will add the item to the new array even_num
  4. After iterating through all the elements, it will log the resultant even_num array to the console.

Learn the Ins & Outs of Software Development

Caltech Coding BootcampExplore Program
Learn the Ins & Outs of Software Development

JavaScript Array Filter(): Examples

Let’s look at some more examples of array filter in JavaScript to understand the concept better.

Example 1: Using Array Filter In JavaScript With Arrow Functions

We can use an array filter in JavaScript to make the code even shorter and easier to understand. In the below example, we will create an array of people objects and filter out the objects with an age greater than 18.

let people = [

    {name: 'Rachel', age: 24},

    {name: 'David', age: 16},

    {name: 'Aakash', age: 23},

    {name: 'Franklin', age: 26},

    {name: 'Ricky', age: 17}

];

let adults = people.filter(big => big.age >= 18);

console.log(adults);

Output:

Array_Filter_in_JavaScript_2.

Example 2: Filtering Prime Numbers Using Array Filter In JavaScript

Until now, we have seen examples where we were defining a function while declaring the array.filter method. This time, we will define a function first and then use it with the filter method to filter out only the prime numbers to the new array.

const myArray = [-5, -4, 1, 3, 7, 12, 13, 15, 17, 21, 23, 25, 27, 30];

function findPrime(item){

  for (let x = 2; item > x; x++) {

    if (item % x == 0) {

      return false;

    }

  }

  return item > 1;

}

console.log(myArray.filter(findPrime));

Output:

Array_Filter_in_JavaScript_3.

Example 3: Filtering Values Within a Range Using Array Filter In JavaScript

For this example, we will be declaring an array of different elements and then filter out only the numeric items within the given range.

function withinRange(item) {

    if (typeof item !== 'number') {

        return false;

    }

    return item >= this.minRange && item <= this.maxRange;

}

let myArray = [1, 5, "this", 12, "is", 23, 29, "35", "Simplilearn", 50];

let rangeLimit = {

    minRange: 1,

    maxRange: 30

};

let filteredArray = myArray.filter(withinRange, rangeLimit);

console.log(filteredArray);

Output:

Array_Filter_in_JavaScript_4

Here's How to Land a Top Software Developer Job

Full Stack Developer - MERN StackExplore Program
Here's How to Land a Top Software Developer Job

Example 4: Filtering String Array Using JavaScript Array Filter

In this example, we will declare an array with car names and filter out the elements with the desired characters in the string.

let cars = ['Mercedes-Benz', 'Ranger', 'Lamborghini', 'Ferrari', 'Mahindra']

function myFunc(myArray, searchCriteria) {

  return myArray.filter(function(item) {

      return item.toLowerCase().indexOf(searchCriteria.toLowerCase()) !== -1

  })

}

console.log(myFunc(cars, 'er'))

Output:

Array_Filter_in_JavaScript_5

Limitations of JavaScript Array Filter()

Besides having several benefits, the JavaScript array filter method has some limitations too, which are:

  • Since the filter method does not mutate the original array, we need to save the filtered array to work with it later.
  • The array filter method does not work if the array does not have any elements in it.

Browsers That Support Array Filter In JavaScript

Following is the list of browsers that support the use of the JavaScript array filter method.

  • Google Chrome
  • Microsoft Edge 9
  • Mozilla Firefox 1.5
  • Opera 9.5
  • Safari 3

Conclusion

In this article, you have learned everything about the JavaScript array filter(). You can learn more such JavaScript fundamentals by referring to Simplilearn’s JavaScript Tutorial. However, if you want to add credibility to your programming skills, it is best to opt for our Post Graduate Program In Full Stack Web Development. It is a self-paced training program that helps you master JavaScript programming and pursue a substantial career in it.

In today’s competitive world, employers are looking for professionals who are well-versed with multiple programming languages. You can achieve this by signing up on our SkillUp platform and opting for our Full-Stack Web Development Certification Course. The SkillUp platform provides free online courses for multiple programming languages, including JavaScript. On the other hand, the Full-Stack Web Development Certification course is an all-inclusive training program that helps you get acquainted with the fundamentals of the most popular development languages. When you complete the course, you will receive your certification and be ready to start a career in software and web development.

If you have any questions or queries, feel free to post them in the comments section below. Our team will get back to you at the earliest.

About the Author

SimplilearnSimplilearn

Simplilearn is one of the world’s leading providers of online training for Digital Marketing, Cloud Computing, Project Management, Data Science, IT, Software Development, and many other emerging technologies.

View More
  • Disclaimer
  • PMP, PMI, PMBOK, CAPM, PgMP, PfMP, ACP, PBA, RMP, SP, and OPM3 are registered marks of the Project Management Institute, Inc.