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.
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!
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.
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 .
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With