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++;
}
}
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With