Solve - filter is not a function Error in JavaScript

avatar

Borislav Hadzhiev

Tue Oct 19 20212 min read

Solve - filter is not a function Error in JavaScript #

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.

typeerror filter is not a function

Here is an example of how the error occurs.

index.js
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.

index.js
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.

index.js
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.

If the value is fetched from a remote server, make sure it is of the type you expect it to be by logging it to the console and make sure you have parsed it to a native JavaScript array before calling the 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.

index.js
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.

index.js
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.

If the error persists, 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.

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee