Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does console tell me that .filter is not a function? [closed]

Tags:

var str = "I am a string.";

console.log(str.split(''));

var fil = function(val){
return val !== "a";
};

console.log(str.filter(fil));

When I run this, it says the str.filter is not a function.

like image 424
Eric Zayas Avatar asked Jun 13 '16 02:06

Eric Zayas


People also ask

What is not a function of filter?

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. Copied!

What is .filter JavaScript?

The filter() method creates a new array filled with elements that pass a test provided by a function. The filter() method does not execute the function for empty elements. The filter() method does not change the original array.

Does .filter mutate?

filter() does not mutate the array on which it is called. The range of elements processed by filter() is set before the first invocation of callbackFn .

Can you use .filter on an array of objects?

The filter() method takes a callback parameter, and returns an array containing all values that the callback returned true for. That makes it easy to use for filtering an array of objects.


2 Answers

Because filter is an array function (Array.prototype.filter), while you are calling it on a string. str.split returns an array and doesn't change anything to your str. call it like console.log(str.split('').filter(fil)) and it should be fine.

like image 110
ali404 Avatar answered Sep 17 '22 18:09

ali404


Because you're invoking the execution of "filter" on str, which is an object without a function called "filter" of its own nor by prototype. Since filter is not present the property's value is undefined, which cannot be invoked because its type is not function.

like image 22
tempoc Avatar answered Sep 18 '22 18:09

tempoc