简体   繁体   中英

How to find total sum of an array then checking if its odd or even in javascript?

I wrote the following code which works for cases with the array has more than one element. How could I make it work when the array consist of just one element?

The below works for [1,23,4,5] but not for [0], [2], 1

 function oddOrEven(array) { var sum = array.reduce(function(acc, intialvalue) { return acc + intialvalue; }); if (sum % 2 == 0) { return "even" } else { return "odd" } } console.log(oddOrEven([1,23,4,5])) console.log(oddOrEven([0])) console.log(oddOrEven([1])) 

请检查此屏幕截图

As the error says, you must have an initial value, 0 in our case.

 function oddOrEven(array) { var sum = array.reduce(function(acc, intialvalue) { return acc + intialvalue; }, 0); if (sum % 2 == 0) { return "even" } else { return "odd" } } console.log(oddOrEven([1,23,4,5])) console.log(oddOrEven([0])) console.log(oddOrEven([1])) 

No initial value means you need to set the initial value of the reduce funtion as 0.

function oddOrEven(array) {
  var sum = array.reduce(function(acc, value) {
    return acc + intialValue;
  }, 0); // <- set the reduce functions initial value

  if (sum % 2 == 0) {
    return "even";
  } else {
    return "odd";
  }
}

You can clean this code up a little by re-writing it as

const oddOrEven = (array) => {
  const sum = array.reduce((acc, value) => acc + value, 0);

  return (sum % 2 == 0) ? "even" : "odd";
};

As others have pointed out, you will need to pass an initial value to reduce .

As an alternate solution, you could just count whether there are are an even or number of odd elements in the array.

 const oddOrEven = (array) => array.reduce((a, i) => i % 2 ^ a, 1) ? "even" : "odd"; console.log(oddOrEven([1,23,4,5])) console.log(oddOrEven([0])) console.log(oddOrEven([1])) 

Consider the following truth table:

x    y    | x+y
----------|-----
even even | even
even odd  | odd
odd  even | odd
odd  odd  | even

Give an initial value to your reduce call. You could also handle the case of an empty array, here I return undefinef:

 const oddOrEven = arr => arr.length ? arr.reduce((sum, x) => sum + x, 0) % 2 === 0 ? 'even' : 'odd' : undefined; console.log(oddOrEven([1, 23, 4, 5])) console.log(oddOrEven([0])) console.log(oddOrEven([1])) console.log(oddOrEven([])) 

Bitwise & can be used to check even and odd

 function oddOrEven(array) { var sum = array.reduce((op, inp) => op + inp, 0); return sum & 1 ? 'odd' : 'even' } console.log(oddOrEven([1,23,4,5])) console.log(oddOrEven([0])) console.log(oddOrEven([1])) 

For the one-line lovers

 const oddOrEven = a => a.reduce((o,i) => o + i, 0) & 1 ? 'odd' : 'even' console.log(oddOrEven([1,23,4,5])) console.log(oddOrEven([0])) console.log(oddOrEven([1])) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM