Borislav Hadzhiev
Tue Oct 19 2021·2 min read
Photo by Brynja Magnusson
The "filter is not a function" error occurs when we call the filter()
method
on a value that is not of type array. To solve the error, convert the value to
an array before calling the filter
method or make sure to only call the method
on arrays.
Here is an example of how the error occurs.
const arr = {}; // ⛔️ Uncaught TypeError: arr.filter is not a function const result = arr.filter(element => element % 2 === 0);
We called the Array.filter method on an object and got the error back.
To solve the error, console.log
the value you're calling the filter
method
on and make sure it's a valid array.
const arr = [4, 6, 11]; const result = arr.filter(element => element % 2 === 0); console.log(result); // 👉️ [4, 6]
Alternatively, you can check if the value is an array by using the Array.isArray method.
const arr = null; const result = Array.isArray(arr) ? arr.filter(num => num % 2 === 0) : []; console.log(result); // 👉️ []
We used a ternary operator, which is very similar to an if/else
statement.
If the value is an array, we return the result of calling the filter
method on
it, otherwise we return an empty array. This way, you won't get an error, even
if the value is not an array.
filter
method on it.If you're trying to use the filter
method on an object, use the
Object.values()
method to get an array of the object's values and use the
filter
method on the array.
const obj = {a: 2, b: 4, c: 13}; const values = Object.values(obj); console.log(values); // 👉️ [2, 4, 13] const result = values.filter(num => num % 2 === 0); console.log(result); // 👉️ [2, 4]
The Object.values
method returns an array of the object's values. We can then
safely call the filter
method on the array and filter out the results.
If you have an array-like object which you're trying to convert to an array
before calling the filter
method, use the Array.from
method.
const set = new Set([8, 2, 3]); const result = Array.from(set).filter(element => element % 2 === 0); console.log(result); // 👉️ [8, 2]
We converted the value to an array before calling the filter()
method.
console.log
the value you're calling the filter
method on and make sure it's an array.If the value is an object, you should probably be accessing a specific property on it, which has a value of an array.