Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

reduce function gives me undifined after second iteration

I’m a bit new to javascript world and I’m really confused by this piece of simple code and don’t know what is the exact problem.
I want to pull out all the colors and add them to a new array.
here is my code:

const data = [
  {a: 'happy', b: 'robin', c: ['blue','green']}, 
  {a: 'tired', b: 'panther', c: ['green','black','orange','blue']}, 
  {a: 'sad', b: 'goldfish', c: ['green','red']}
];


const colors = data.reduce((total,item)=>{
  let tempArr = item.c
  total.push(...tempArr)
},[]) 

console.log(colors)

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

A function that doesn’t contain a return will return undefined. Your reduce callback doesn’t contain a return. Fix with

return total;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading