Get the number of non-empty elements from nested arrays

I have ten arrays with an empty value

onTable[0 to 10]; 

take a look

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

I want to get the length of each array without an empty value and not create ten variables to check this.

I tested this solution to read empty values ​​in an array , but I do not want to do ten variables. i.e.: count1, count2,...

I also check the comparison of two arrays based on length: skip empty values , but this is not what I want.

If possible, I want it to look like

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

What is a good way to do this?

+5
source share
4 answers

Use filter with Boolean to filter non-empty elements from the submatrix and use length on it.

 onTable[0].filter(Boolean).length 

Since the empty string is false in JavaScript, it will be removed from the filtered array.

Demo:

 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); 
+8
source

Using 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> 
+1
source

You can use the filter function for your need: check the value for undefined or null , etc.

 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); 
0
source

You should avoid wasting memory and cause excessive GC. You can reduce() each additional array to count its non-empty values:

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

To process the entire main array, you can map() its lengths:

 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('], [') + ']'); 
0
source

Source: https://habr.com/ru/post/1236321/


All Articles