Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter is not a function? [duplicate]

Tags:

javascript

Im attempting to return an array of my list items if they contain the text "Flexbox" in them.

Im getting this error: Uncaught TypeError: items.filter is not a function

    <ul>
        <li data-time="5:10">Flexbox 1</li>
        <li data-time="5:10">Something else</li>
        <li data-time="5:40">Flexbox 2</li>
        <li data-time="5:10">Something also else</li>
        <li data-time="5:40">More Flexbox for you</li>
    </ul>


'use strict';

var items = document.querySelectorAll('li');

var itemsFlex = items.filter(function(item) {
    return item.includes('Flexbox')
});

console.log(itemsFlex);
like image 765
Evanss Avatar asked May 12 '17 02:05

Evanss


People also ask

Which is not 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!

Can you filter an object JavaScript?

Unfortunately, JavaScript objects don't have a filter() function. But that doesn't mean you can't use filter() to filter objects, you just need to be able to iterate over an object and convert the object into an array using Object. entries() .


2 Answers

querySelectorAll returns a NodeList not an Array. You can convert it to an Array if you'd like to use Array methods.

var items = document.querySelectorAll('li');
var itemsArray = Array.from(items);
like image 111
Jordan Soltman Avatar answered Sep 29 '22 00:09

Jordan Soltman


The querySelectorAll does not return an array, that is the reason why filter is not defined (which is a function of array). In this case, you should call filter function from Array.prototype and use textContent.indexOf(string) to check if the element has the text content you want (Flexbox). For sample:

var items = document.querySelectorAll('li');
var filter   = Array.prototype.filter;

var itemsFlex = filter.call(items, function(item) {
    return item.textContent.indexOf('Flexbox') >= 0;
});

console.log(itemsFlex);

See the sample here: https://jsbin.com/hibixipoyo/edit?html,js,output

like image 45
Felipe Oriani Avatar answered Sep 28 '22 22:09

Felipe Oriani