简体   繁体   中英

Codewars 'odd or even?' on JavaScript

Task: Given a list of numbers, determine whether the sum of its elements is odd or even.

Give your answer as a string matching "odd" or "even".

If the input array is empty consider it as: [0] (array with a zero). My code:

 function oddOrEven(array) {
  return array.reduce( function (sum, item) { return sum + item }) % 2 == 0 ? 'even': 'odd';
} 

My problem:
Passed: 14 Failed: 1 Errors: 1 Exit Code: 1
TypeError: Reduce of empty array with no initial value
Why?

Alright, my problem was that i didn't make an initialValue like '0'
My answer:
function oddOrEven(array) { return array.reduce( function (sum, item) { return sum + item }, 0) % 2 == 0? 'even': 'odd'; }

You need to provide an initial value for the reduce accumulator. reduce(accFunc, initialAccValue) , like this:

 function oddOrEven(array) { return array.reduce(function(sum, item) { return sum + item }, 0) % 2 == 0? 'even': 'odd'; } console.log(oddOrEven([1, 2])); console.log(oddOrEven([1, 3])); console.log(oddOrEven([]));

This is the sintax of the function reduce:

arr.reduce(callback(accumulator, currentValue[, index[, array]]) [, initialValue])

In order to avoid this error, you need to specify the initialValue .

In your example should be 0 :

   function oddOrEven(array) {
      return array.reduce( function (sum, item) { return sum + item }, 0) % 2 == 0 ? 'even': 'odd';
    } 

Check the documentation for Reduce .

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