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
]
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);
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments