简体   繁体   中英

How to use reduce to return an object in Javascript?

I'm trying to count the number of odd and even numbers in an array by using the Array.reduce() method. When I run the below code, I get the error "odd is not defined." How/where do I define odd to get this code to work?

var numbers = [5, 3, 8, 6, 9, 1, 0, 2, 2];
var oddEvenCounts = numbers.reduce(function(counts, number) {
   if (number % 2 === 1) {
     counts[odd]++
   } else {
     counts[even]++;
   }
   return counts;
 }, {});

Well, odd isn't defined. What you should do is either put odd/even in quotes ( counts['odd'] ) or use dot notation ( counts.odd ).

Also, since odd and even aren't defined, incrementing them would result into NaN . The initial value should instead be { odd: 0, even: 0 } .

 var numbers = [5, 3, 8, 6, 9, 1, 0, 2, 2]; var oddEvenCounts = numbers.reduce(function(counts, number) { if (number % 2 === 1) { counts['odd']++; } else { counts['even']++; } return counts; }, { odd: 0, even: 0 }); console.log(oddEvenCounts); 

This is a function that can do it for you.

 function oddEvenCounts(arr) { const counts = { even: 0, odd: 0 }; arr.forEach(n => { if(n % 2 === 0) { counts.even++; } else { counts.odd++ } }); return counts; } const array = [5, 3, 8, 6, 9, 1, 0, 2, 2]; console.log(oddEvenCounts(array)); 

Answer using ES6+

const sumEvenOdd = (numbersArray) => {
    return numbersArray.reduce((acc, current) => current % 2 === 0 ? {...acc,'even':acc['even'] + current} : {...acc, 'odd':acc['odd'] + current}, {"even":0, "odd":0})
}'

console.log(sumEvenOdd([1, 6, 8, 5, 3]));
// Expected results: {even: 14, odd: 9}

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