Kesem David Kesem David - 1 year ago 60
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

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

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
s in a separate array achieved with a

Thanks in advance :)

Answer Source

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) {

// 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);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download