从嵌套数组中获取非空元素的数量

时间:2015-11-19 11:39:00

标签: javascript jquery arrays

我有十个空值

的数组
onTable[0 to 10];

["Jean5", "Jean3", "Paul2", "Jean6", "", "Paul4", "Jean", "peirre4", ""]
["Paul5", "peirre6", "peirre3", "", "Jean4", "Paul", "peirre5", "Jean2", ""]
...

我希望获得每个数组的长度而没有空值,并且没有创建十个变量来检查。

我测试了这个解决方案 count empty values in array但我不想让十变量。即:count1, count2,...

我也检查compare two arrays based on length: skip empty values但不是我想要的。

如果可能的话,我希望看起来像

onTable[0].length(exclude(""))

制作它的好方法是什么?

4 个答案:

答案 0 :(得分:11)

使用filterBoolean一起过滤子数组中的非空元素,并在其上使用length

onTable[0].filter(Boolean).length

由于JavaScript中的空字符串是假的,所以它将从过滤后的数组中删除。

<强>演示:

&#13;
&#13;
var arr = [
  ["Jean5", "Jean3", "Paul2", "Jean6", "", "Paul4", "Jean", "peirre4", ""],
  ["Paul5", "peirre6", "peirre3", "", "Jean4", "Paul", "peirre5", "Jean2", ""]
];

var len = arr[1].filter(Boolean).length;
document.write(len);
&#13;
&#13;
&#13;

答案 1 :(得分:1)

使用prototype

Array.prototype.lengthWihtoutEmptyValues = function () {
    var initialLength = this.length;
    var finalLength = initialLength;

    for (var i = 0; i < initialLength; i++) {
        if (this[i] == "") {
            finalLength--;
        }
    }

    return finalLength;
}

var arrays = [
  ["Jean5", "Jean3", "Paul2", "Jean6", "", "Paul4", "Jean", "peirre4", ""],
  ["Paul5", "peirre6", "peirre3", "", "Jean4", "Paul", "peirre5", "Jean2", ""]
];

var arrayLength = arrays[0].lengthWihtoutEmptyValues();

$("#arrayLength").html(arrayLength);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="arrayLength"></div>

答案 2 :(得分:0)

您可以根据需要使用过滤功能:检查undefinednull等值。

var arr = [
  ["Jean5", "Jean3", "Paul2", "Jean6", "", "Paul4", "Jean", "peirre4", ""],
  ["Paul5", "peirre6", "peirre3", "", "Jean4", "Paul", "peirre5", "Jean2", ""]
];

var len = arr[1].filter(function(x){ return x != ""}).length;
document.write(len);

答案 3 :(得分:0)

你应该避免“浪费”记忆并诱导过多的GC。你可以reduce()每个子数组计算它的非空值:

sub.reduce(function(prev, cur) {
  return prev + (!!cur);
}, 0);

为了处理整个主数组,您可以map()使用它的长度:

var arr = [
  ["Jean5", "Jean3", "Paul2", "Jean6", "", "Paul4", "Jean", "peirre4", ""],
  ["Paul5", "peirre6", "peirre3", "", "Jean4", "Paul", "peirre5", "Jean2", ""],
  ["Just1", "", ""]
];

var lengths = arr.map(function(sub) {
  return sub.reduce(function(prev, cur) {
    return prev + (!!cur);
  }, 0);
});
document.write('[' + lengths.join('], [') + ']');