JavaScript Filter Array() Method to Filter Complex Arrays in an Easy Way

Article By Digamber Rawat on

JavaScript Filter

JavaScript filter method is used to create a new array from an existing array. The JavaScript filter() method returns a new array which will be filtered from an original array. You will be performing a certain test on an original array and the elements that pass this test will be returned to the new array using this method.

JavaScript filter syntax:

let myArray = array.filter(callback(element[, index[, arr]])[, thisArg])
  • myArray – The new array which is going to be returned.
  • array – You will be running the filter function on this array.
  • callback – You will be employing this function to see if the elements in the array pass certain test or not. If it returns true then the element will be added to the myArray, else it will be omitted.

Speaking of the callback function of JavaScript filter, it takes 3 arguments. Let’s have a look below:

  • element – We are referring to the current element here.
  • index – We are referring to current index of the value we are processing.
  • arr – Here we are referring to the original array.

As we all know, developers work with arrays on a daily basis. It’s nothing new to them. And filtering an array is one of the common chores. Developers often have to create a new array by filtering the elements of an existing array.

If you wish to see how manual filtering works, here is how it looks like:

var superHeros = [
{ name: "Robert Downey, Jr.",  hero: "Iron Man" },
{ name: "Chris Evans", hero: "Captain America" },
{ name: "Mark Ruffalo", hero: "Hulk"   },
{ name: "Tom Hiddleston", hero: "Loki" }
];
var heroArray = [];
for (var i = 0; i < superHeros.length ; i++) {
if (superHeros[i].hero === "Loki") {
heroArray.push(superHeros[i]);
}
}
console.log(heroArray);
// Outputs: [
//    { name: "Tom Hiddleston", hero: "Loki" }
// ]
But thankfully, we have JavaScript filter method to filter elements from an existing array. There is no need to manually go through each element in the array ourselves.

var superHeros = [
{ name: "Robert Downey, Jr.",  hero: "Iron Man" },
{ name: "Chris Evans", hero: "Captain America" },
{ name: "Mark Ruffalo", hero: "Hulk"   },
{ name: "Tom Hiddleston", hero: "Loki" }
];
var newArray = superHeros.filter(function (element) {
return (element.hero === "Hulk");
});
console.log(newArray);
// Result: [
//    { name: "Mark Ruffalo", hero: "Hulk"   }
// ]

As we have stated before, filter methods makes use of callback function. The callback function is responsible for examining each element individually before returning true if the element passes the test.

Another good thing about callback function is that it can access an element with the index of the element as well. It also has access to the full array.

Let’s have a look:

var newArray = superHeros.filter(function (element) {
// Filtering works here
});

Thanks to this feature, you will find it easy to create more complex filters. You will be able to explore the relationship between the elements.

We have already told you that this filter method returns an array. Considering that, you will be able to chain filter method with other methods like map and sort.

Let’s take a look at an example below:

let superHeros = [
{ name: "Robert Downey, Jr.",  hero: "Iron Man" },
{ name: "Chris Evans", hero: "Captain America" },
{ name: "Mark Ruffalo", hero: "Hulk"   },
{ name: "Tom Hiddleston", hero: "Loki" }
];
let newArray = superHeros.filter(function (element) {
return (element.hero === "Captain America");
}).map(function(el) {
return el.name;
}).sort()
console.log(newArray);
// ["Chris Evans"]

Filter method belongs to the ECMAScript 5 specification. As a result, it is not supported by the older browsers such as IE8. But if you wish to use it in older browsers, then you may take the help of a compatibility shim. Or you can rely on similar filter methods like Lo-Dash or Underscore in a library.

Another JavaScript Filter Example

It’s time for us to inspect a complex example for JavaScript Filter. We have chosen an array of objects for the same. We are going to work with the following data:

let employees = [
{
name: "John",
salary: 8000
},
{
name: "Jeff",
salary: 7000
},
{
name: "Dave",
salary: 7500
},
{
name: "Amber",
salary: 5000
},
{
name: "Cassie",
salary: 4500
},
{
name: "Albert",
salary: 12000
},
{
name: "Kate",
salary: 9000
},
{
name: "Tony",
salary: 3000
},
{
name: "Lisa",
salary: 1150
},
{
name: "Jenna",
salary: 2500
}
]

We are planning to create a new array where we filter the names of the employee with less than 8500. In order to do this we are going to test the data in our hand.

let salary = employee.filter(data => {
return data.salary > 8500;
});

All that we have used is two lines of codes to make sure that only the largest salary taker found a place on the list. Even though we are dealing with complex data here, the process to filter stays pretty much the same. Following is what we got after running the filter function.

Let’s have a look below.

// Salary taker more than 8500 from the employees list
{
name: "Albert",
salary: 12000,
married: true
},
{
name: "Kate",
salary: 9000,
married: true
}

JavaScript Filter using Fat Arrow Function in ECMAScript 6

All thanks to the entry of arrow functions in ECMAScript, it has become even simpler to use array filter JavaScript. Let’s examine the above code wherein we filter employee records with a salary more than 8500.

Let’s examine the code below:

let highestSalary = employee.filter(data => {
return data.salary > 8500;
})

The arrow function is already in use here. But we can clean up the JavaScript array filter() method even more. Let’s assume that we are returning a value from an arrow function. In order to show that you are returning the value itself, you can get rid of the brackets in the function.

As in the previous code segment, this code is designed to test each value in the array. It will try to see if the salary of the employee is more than 8500 or not. Whenever the method returns a true value, the particular element will be added to the new array.

I hope that you have got some idea as how to use filter JavaScript method in your code segment.

Digamber Rawat

Feel free to contact me, If you are looking for a freelance full stack Developer, with the following skills: Mongo DB, Express JS, Angualr 2+, Node JS, Loopback JS, Firebase, Ionic Framework and WordPress. I also offer remote contracting service to the clients across the globe. Hire Me