Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

204
Views
how to get sum of odd, even numbers using Array.reduce method?

how to get sum of odd, even using reduce method, i have done as show in below code but returning undefined , @js-beginner

//code below

nums= [1,2,3,4,5,6,7,8,9]

function getOddEvenSum(numbers){     
    let{even,odd} = numbers.reduce((acc, cuu) => cuu%2 === 0?acc.even + cuu:acc.odd+cuu,{even:0, odd:0})

    return {even, odd}
  }

console.log(getOddEvenSum(nums)

//output i am getting below

{even:undefined, odd:undefined}
about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

You can use Array.prototype.reduce like this:

const nums = [1, 2, 3, 4, 5, 6, 7, 8, 9];

const [odds, evens] = nums.reduce(
  ([odds, evens], cur) =>
    cur % 2 === 0 ? [odds, evens + cur] : [odds + cur, evens],
  [0, 0]
);

console.log(odds);
console.log(evens);

about 4 years ago · Juan Pablo Isaza Report

0

The value that you return from your reduce callback will be the value of acc upon the next invocation/iteration of your array of numbers. Currently, your acc starts off as an object, but as you're only returning a number from your first iteration, all subsequent iterations will use a number as acc, which don't have .even or .odd properties. You could instead return a new object with updated even/odd properties so that acc remains as an object through all iterations:

const nums = [1,2,3,4,5,6,7,8,9];

function getOddEven(numbers){     
  return numbers.reduce((acc, cuu) => cuu % 2 === 0
    ? {odd: acc.odd, even: acc.even + cuu}
    : {even: acc.even, odd: acc.odd+cuu},
  {even:0, odd:0});
}

console.log(getOddEven(nums));

about 4 years ago · Juan Pablo Isaza Report

0

This is not how the syntax of reduce works. One possible implementation:

function getOddEven(nums) {
  return nums.reduce(
    ({odd, even}, num) => num % 2 === 0 ?
      {odd, even: even + num} :
      {odd: odd + num, even},
    {odd: 0, even: 0},
  );
}

I would argue that this is not very clear. Since performance is probably not critical, a clearer alternative would be:

function getOddEven(nums) {
  return {
    odd: nums.filter(num => num % 2 == 1).reduce((acc, num) => acc + num),
    even: nums.filter(num => num % 2 == 0).reduce((acc, num) => acc + num),
  };
}
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!