Filter Array in Javascript

cover-photo

Filter Array in Javascript


In this post we are going to learn how to use Array.filter() in Javascript. So the first we need to understand the use of Array.filter(). So most of the times we need to create a subset of an array or a new array where we need some of the values from the actual array depending upon a certain criteria/condition.

So the first thing comes to mind is to loop through the array and push all the items into new array depending upon the condition. But this is time consuming and not considerate.

Instead Javascript provides us Array.filter() method which does the same job in much cleaner approach. This method creates new array with all elements that pass the test implemented by the provided function.

In Below example we have created a function checkWord() which returns the word if its character length is greater than 6. This function checkWord() is invoked by filter() method for each item in the array words. The checkWord() function is known as callback for filter() method and is invoked by filter() method for each index in array which have value (eg: not null);

const words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];

function checkWord(item) {
  return item.length > 6;
}

const result = words.filter(checkWord); 

console.log(result); // ["exuberant", "destruction", "present"]

This above example can be simplified by using arrow function as below, here we don't need to write an extra function checkWord() like we did before just use the arrow function instead as below.

const words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];

const result = words.filter(item => item.length > 6); 

console.log(result); // ["exuberant", "destruction", "present"]


We can also use filter Method on Array of Objects, let's take a look at example below.

const cars = [{
        "Name": "chevrolet chevelle malibu",
        "Horsepower": 130,
        "Year": "1970-01-01",
    },
    {
        "Name": "buick skylark 320",
        "Horsepower": 165,
        "Year": "1970-01-01",
    },
    {
        "Name": "plymouth satellite",
        "Horsepower": 150,
        "Year": "1970-01-01",
    },
    {
        "Name": "amc rebel sst",
        "Horsepower": 150,
        "Year": "1970-01-01",
    },
    {
        "Name": "ford torino",
        "Horsepower": 140,
        "Year": "1970-01-01",
    },
    {
        "Name": "ford galaxie 500",
        "Horsepower": 198,
        "Year": "1970-01-01",
    }
];

const data = cars.filter(car => car.Horsepower > 170); 

console.log(data); //output [{Name: "ford galaxie 500", Horsepower: 198, Year: "1970-01-01"}]

Hope you have understood the working of Array.filter() in Javascript.


Happy Coding!