Kesem David Kesem David - 18 days ago 6
TypeScript Question

How to efficiently get a collection that contains multiple nested collections

Title might not be the best, an improvement would be much appreciated!

What i mean is actually very simple question:

Say i have a

School
class containing an array of
Student
s that has an array of
Notebook
s, and i want to refer all the
Notebook
s in my
School


public class School{
students: Student[];
}

public class Student{
notebooks: Notebook[]
}


How should i refer to all of the Notebooks in my school?

Looking for a more efficient way from saving all the
Notebook
s in a separate array achieved with a
for
loop..


Thanks in advance :)

Answer

It all depends on what you want to do with the output or each individual notebook? This function closely replicates to for loops without all the boilerplate.

school.students.forEach(function(student) {
  student.notebooks.forEach(function(notebook) {
    doSomethingWithNotebook(notebook);
  });
});

// this returns all notebooks for all students and puts it into a single (flat) array
var allNotebooks = school.students.reduce(function(collection, student) {
  return collection.concat(sudent.notebooks);
}, []);

// now you can do things like filter out only New notebooks
var newNotebooks = allNotebooks.filter(notebook => notebook.isNew);