My problem goes this way; I have an array of courses, each one has its name and array consisting of lessons (Each lesson has its own days).
I.e.:
courses = [
{name: 'Math', lessons: [{day: 'Wednesday'}, {day: 'Thursday'}]},
{name: 'Sports', lessons: [{day: 'Monday'}]}
]
My desired result is:
courses_flattened = [
{name: 'Math', lesson: {day: 'Wednesday'}},
{name: 'Math', lesson: {day: 'Thursday'}},
{name: 'Sports', lesson: {day: 'Monday'}}
]
Currently what I'm doing is using array.map to iterate over the courses, then for each course I'm returning an array consisting of all lessons times. After receiving an array of arrays, I'm using:
courses_flattened = [].concat.apply([], courses_flat)
to get an array consisting of all courses with 1 lesson each.
Full code:
courses_flat = courses.map((course) -> {
var lessons = [];
course.lessons.forEach((lesson) -> {
lessons.push({name: course.name, lesson: {day: lesson.day}})
});
return lessons;
});
Is there a nicer way for receiving this kind of result?
Using Lodash is an option for me.