1
\$\begingroup\$

All I am trying to achieve is better use of built-in ES functions.

var arr = [0, 1, 2, 3, -1, -2, -3];

function countPositiv(p, c, i, a)
{ 
  if(c > 0){
    return p+1; 
  } else {
    return p;
  }
}

var positiv = arr.reduce(countPositiv, 0);

console.log(positiv);
\$\endgroup\$
1
  • \$\begingroup\$ Welcome to Code Review! I hope you get some helpful reviews. \$\endgroup\$ – SirPython Jan 25 '16 at 23:34
1
\$\begingroup\$

I don't think there is much to review, it looks ok. I would just do it inline, and there is no need to list arguments you are not using:

var positiv = arr.reduce(function(acc, x) {
  return x > 0 ? acc + 1 : acc;
}, 0);
\$\endgroup\$
1
\$\begingroup\$

This can easily be done using filter and length. filter creates an array comprising of values where the callback returned true. In this case, when v > 0. And since filter returns an array, we have access to length.

let positiveNumbersCount = arr.filter(v => v > 0).length;
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.