Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

constructing more complex for-loops

Tags:

javascript

How to put the k var in the for-loop construction. I want more compact code, not like this one:

var k = 0;
for (var i = 0; i < arr.length; i++) {
   if (arr[i] == 'x') {
       k++;
   }
}
like image 595
anon Avatar asked May 01 '26 15:05

anon


1 Answers

Although not as efficient due to the fact that a new array is constructed, using filter leads to far more compact code.

arr.filter(function(e){ return e == 'x'; }).length;

An alternative, although far less clear avoids constructing a new array:

arr.reduce(function(x, e){ return x + (e == 'x' ? 1 : 0); }, 0);
like image 67
Yacoby Avatar answered May 04 '26 05:05

Yacoby



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!