Member-only story
Get length of a 2D Array of objects in Typescript
1 min readAug 8, 2023
I recently encountered the problem that I had an array of Objects that each with a property that is another array. In my case I have a book, the book consists of chapters that each have pages. So how can I simply get the total number of pages a book has if I have an array with the chapters without using some awful for loops?
The answer is array.flatMap().length!
I couldn’t quickly find the answer so I decided to write this short post to help future me because I’m sure I’ll have forgotten it by tomorrow…
class Chapter {
name: string;
sheets: sheet[];
}
class Sheet {
name: string;
}
let chapter1 = new Chapter()
chapter1.sheets = [new Sheet(), new Sheet(), new Sheet(), new Sheet()]
let chapter2 = new Chapter()
chapter2.sheets = [new Sheet(), new Sheet(), new Sheet())]
let chapter3 = new Chapter()
chapter3.sheets = [new Sheet()]
let chapter4 = new Chapter()
chapter4.sheets = [new Sheet(), new Sheet(), new Sheet(), new Sheet(), new Sheet()]
let book = [ chapter1, chapter2, chapter3, chapter4];
let sheetsInBook = book.flatMap(chapter => chapter.sheets).length
console.log(sheetsInBook) // 13
Don’t forget to visit my website https://www.alexschnabl.com/ for more content!