Tutorial Playlist

JavaScript Tutorial: Learn JavaScript from Scratch

Overview

An Introduction to JavaScript: Here Is All You Need to Know

Lesson - 1

JavaScript Hello World: Here's What You Need To Know

Lesson - 2

All You Need to Know About JavaScript Arrays

Lesson - 3

Using Array Filter In JavaScript to Filter Array Elements

Lesson - 4

Everything You Need to Know About Array Reduce JavaScript

Lesson - 5

Introduction To JavaScript Loops: Do-While, For, For-In Loops

Lesson - 6

All You Need to Learn About Javascript Functions

Lesson - 7

The Best Guide on How to Implement JavaScript Closures

Lesson - 8

JavaScript “This” Keyword and How to Implement It

Lesson - 9

How to Implement JavaScript Form Validation

Lesson - 10

An Introduction Guide To JavaScript RegEx

Lesson - 11

How to Validate an Email Address in JavaScript?

Lesson - 12

All You Need to Know About JavaScript Promises

Lesson - 13

How to Implement JavaScript Async/Await

Lesson - 14

JavaScript DOM Tutorial: 2020 Edition

Lesson - 15

JavaScript Objects: Properties, Methods, and Accessors

Lesson - 16

An Introduction to Javascript Games: The Best Guide

Lesson - 17

An Easy Guide To Build A Calculator App In JavaScript

Lesson - 18

Javascript Projects: The Best Guide

Lesson - 19

What is OOP in JavaScript? How is it Implemented?

Lesson - 20

The Best Guide to Understanding JavaScript Learning Path

Lesson - 21

Java Vs .NET: Which Is the Best Technology to Choose?

Lesson - 22

Top 40 JavaScript Interview Questions You Should Know

Lesson - 23

Typeof in JavaScript: Checking Data Types Using the Typeof Operator

Lesson - 24

Tips and Tricks That You Should Know Before Going to a Coding Interview

Lesson - 25

Callback Functions in JavaScript

Lesson - 26
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.

Post Graduate Program: Full Stack Web Development

in Collaboration with Caltech CTMEEnroll Now
Post Graduate Program: Full Stack Web Development

Syntax and Parameter Values of Array Filter In JavaScript

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 Array Filter In JavaScript 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.

Free Course: JavaScript for Beginners

Learn the Basics of JavaScriptEnroll Now
Free Course: JavaScript for Beginners

Array Filter In JavaScript : 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

Full Stack Web Developer Course

To become an expert in MEAN StackView Course
Full Stack Web Developer Course

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 Array Filter In JavaScript

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
Master the complete JavaScript fundamentals, jQuery, Ajax, and more with the Javascript Certification Training Course. Check out the course preview!

Conclusion

In this article, you have learned everything about the array filter in JavaScript. 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 JavaScript Certification Course. 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.

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.