Nicolas Nicolas - 1 month ago 11
Javascript Question

Return the length of a filtered Array

I have this if statement that returns only the results of the array that correspond with the user input. In other words, a search bar for the array.

var filter = userInput.value.toUpperCase();
for (var i = 0; i < myArrayElements.length; i++) {
if (myArrayElements.toUpperCase().indexOf(filter) != -1) {
myArrayElements[i].style.display = 'list-item';
} else {
myArrayElements[i].style.display = 'none';
}
}


I'm wondering how I can return the length of the filtered array. Plus I would like to use that length in the global scope.

I tried this inside the if statement :

var arrayLength = myArrayElements[i].length;
return arrayLength;


and

console.log(myArrayElements[i].length);


But no success either : the console returns an error.

Edit: Nina Scholz answer returns the length of the array properly and the example given is awesome, but the other answers with .filter() are well worth taking into consideration, thanks to you all!

Answer

You could use a variable for the count.

var filter = userInput.value.toUpperCase(),
    count = 0;

for (var i = 0; i < myArrayElements.length; i++) {
    if (myArrayElements[i].toUpperCase().indexOf(filter) != -1)  {
        // ^^^^^^^^^^^^^^^ only if that is really a string!!!
        myArrayElements[i].style.display = 'list-item';
        count++;
    } else {
        myArrayElements[i].style.display = 'none';      
    }
}

Working example:

function find() {    
    var filter = document.getElementById('search').value.toUpperCase(),
        count = 0,
        myArrayElements = document.getElementsByTagName('li');        

    for (var i = 0; i < myArrayElements.length; i++) {
         if (myArrayElements[i].innerHTML.toUpperCase().indexOf(filter) != -1)  {
              myArrayElements[i].style.display = 'list-item';
              count++;
         } else {
             myArrayElements[i].style.display = 'none';      
         }
    }
    console.log(count);
}
<input id="search" > <button onclick="find()">find</button>
<ul>
<li>test</li>
<li>test-case</li>
<li>42</li>
<li>Test</li>
</ul>