Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get number of non-empty elements from nested arrays

I have ten arrays with empty value

onTable[0 to 10];

look

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

I want get length of each array without empty value and without create ten variables for check that.

I have test this solution count empty values in array but i dont want make ten variable. ie: count1, count2,....

I check too compare two arrays based on length: skip empty values but is not what i want.

If possible, I want this look like

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

What is the good way for make that?

like image 719
P. Frank Avatar asked Nov 19 '15 11:11

P. Frank


1 Answers

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

onTable[0].filter(Boolean).length

As empty string is falsy in JavaScript, it'll be removed from 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);
like image 129
Tushar Avatar answered Oct 20 '22 20:10

Tushar