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

How to create an array of objects with all objects from multiple arrays?

Given de following arrays:

const classes = [
  {
    students: [
       Student1,
       Student2,
    ]
  },
  {
    students: [
       Student3,
       Student4,
    ]
  }
]

What’s the best way performance-wise to generate an array of objects with a similar structure to this:

const allStudents = [
  Student1,
  Student2,
  Student3,
  Student4
]

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

>Solution :

Please note: Donot use reserved keyworks such ass class as a variable name.

Array.reduce implementation

const classes = [
  { students: [ 'Student1', 'Student2' ] },
  { students: [ 'Student3', 'Student4' ] }
];
const allStudents = classes.reduce((acc, cls) => {
  acc = cls.students ? acc.concat(cls.students) : acc;
  return acc;
}, []);
console.log(allStudents)

Array.flatMap implementation.

const classes = [
  { students: [ 'Student1', 'Student2' ] },
  { students: [ 'Student3', 'Student4' ] }
]
const allStudents = classes.flatMap((cls) => cls.students ? cls.students : []);
console.log(allStudents);
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