Return the length of a filtered Array

时间:2016-10-20 13:21:14

标签: javascript arrays

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!

3 个答案:

答案 0 :(得分:4)

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>

答案 1 :(得分:0)

您可以使用filter function

  

filter()方法创建一个包含所有传递元素的新数组   由提供的函数实现的测试。

var newArray = myArrayElements.filter(function(value, index, array) {
  return value.toUpperCase() === filter;
});
var newArrayLength = newArray.length;

已经指出(我自己也看到了这个问题,但无论如何回答了问题),这并没有考虑到循环中的逻辑。这可以通过将myArrayElements中的所有元素作为display:none;作为默认值来修复,然后使用:

var newArray.forEach(function(value, index, array) {
  value.style.display = 'list-item';
});

或者您可以使用关闭时的forEach()

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

myArrayElements.forEach(function(value, index, array) {
  (value.toUpperCase() === filter) ? value.style.display = 'list-item' : value.style.display = 'none';
  count ++;
});

答案 2 :(得分:0)

您可以使用var filter = userInput.value.toUpperCase(), filterFunc = function(element) { if (element === filter) { element.style.display = 'list-item'; return true; } else { element.style.display = 'none'; return false; } } var filteredLength = myArrayElements.filter(filterFunc).length; 函数执行样式更改并一次性获取已过滤的数组。

android {
    compileSdkVersion 24
    buildToolsVersion "24.0.2"
    useLibrary  'org.apache.http.legacy'

    defaultConfig {
        applicationId "mchat.sunil.com.mchat"
        minSdkVersion 15
        targetSdkVersion 24
        versionCode 1
        versionName "1.0"
        multiDexEnabled true
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:design:24.2.1'
    compile 'org.igniterealtime.smack:smack-tcp:4.1.0'
    compile 'org.igniterealtime.smack:smack-android-extensions:4.1.0'
    compile 'com.parse:parse-android:1.13.1'
    compile 'org.jitsi:org.otr4j:0.22'
    compile 'com.github.siyamed:android-shape-imageview:0.9.3'
    compile 'com.google.code.gson:gson:2.7'
    compile 'org.simpleframework:simple-xml:2.7.1'

}
configurations {
    all*.exclude group: 'xpp3', module: 'xpp3'
}