fullstackpilot Logo
JavaScript filter js filter javascript filter

JavaScript filter - How to filter the array in JavaScript properly?

Martin Milo
By on

JavaScript filter is another one of the essential methods you can use to loop through the array. The output of this method is a shallow copy of the provided array without the items you filtered out.

Table of Contents

JavaScript filter - how to use it

Let's have a look at how to use the filter array method with some examples.

The filter method accepts a callback function, and optionally, we can pass thisArg (which will be used as this when executing the callback). The callback or provided function is called once on each item in an array in ascending order.

Anonymous function

const avengers = ['Thor', 'Iron man', 'Hulk']
// We passed an anonymous function as a callback to filter
const out = avengers.filter(function (avenger) {
return avenger !== 'Thor'
})
console.log(out)
// -- 👇 console.log output --
// Array(2) ["Iron man", "Hulk"]

You can also rewrite the anonymous function if you want to use the ES6 arrow syntax. This would make it a one-liner:

const out = avengers.filter((avenger) => avenger !== 'Thor')

Callback as non-anonymous function

Although not as common, we can declare the callback as non-anonymous function. It's useful if the callback needs to be reused in our code.

const avengers = ['Thor', 'Iron man', 'Hulk', 'Ant-man', 'Spider-man']
// This function probably won't be needed anywhere else
// but let's pretend it would be
function hasManInName(avenger) {
return avenger.includes('man')
}
const out = avengers.filter(hasManInName)
// ☝️ is shorthand of:
// avengers.filter((avenger) => hasManInName(avenger))
console.log(out)
// -- 👇 console.log output --
/* Array(3) ["Iron man", "Ant-man", "Spider-man"]
*/

JavaScript executes the callback once for every item in the array. There is no difference if we use callback (named function) or anonymous function. In the last example, iterated item (in our case avenger) is passed as a first parameter to the callback implicitly.

Filter with index

Callback or anonymous function we pass to filter has two more optional parameters. First of the optional parameters is the index.

const avengers = ['Thor', 'Iron man', 'Hulk']
const out = avengers.filter(function (avenger, index) {
return index === 0
})
console.log(out)
// -- 👇 console.log output --
/* Array(3) ["Thor"]
*/

Filter array-like objects

Array-like object are topics on their own, so let's just jump on the examples. If you're working in a browser environment with JavaScript, the most common array-like object you probably encounter is a NodeList - you can get it by trying document.querySelectorAll('p'). You may choose to get different element, not necessarily a paragraph.

You can't use filter on NodeList as it would throw Uncaught TypeError: filter is not a function. We need to first convert/copy the array-like object to the array. In the following example, we can see an array-like object:

const avengersInArrayLikeObject = {
"0": "Thor",
"1": "Iron man",
"2": "Hulk",
"length": 3
}

Now in order to filter the avengersInArrayLikeObject, we can't call filter directly. It would throw the same error as with NodeList. We have couple of options though:

// Array-like object on which we can't use (call) filter
// It would throw 'filter is not a function' TypeError
const avengersInArrayLikeObject = {
"0": "Thor",
"1": "Iron man",
"2": "Hulk",
"length": 3
}
// Named function (callback) called 'fn'
function fn(avenger, index) {
return index === 0
}
// Create new shallow copy from an array-like object
// Array.from returns an Array instance
const out1 = Array.from(avengersInArrayLikeObject).filter(fn)
// We can call slice method
const out2 = Array.prototype.slice
.call(avengersInArrayLikeObject).filter(fn)
// We can call filter indirectly by using a call method
const out3 = Array.prototype.filter
.call(avengersInArrayLikeObject, fn)

Conclusion

The filter array method is extremely useful to filter out items from an array in very explicit manner.

You can also put side-effects in the callback you pass to filter but keep in mind that under normal circumstances you can't break the iteration.

There are also several other useful array methods defined by ES5, such as:

I'll link these as soon as I cover them in the separate article. Consider reading up on them, as if you don't you may end up reinventing a method that already exists. For instance some and every are not as well-known as the other array methods.

Did you find the usage of filter easy? Feel free to share a comment down below.

Share: