0

hoping someone can point me in the right direction here. I have to add the pages of each book and get a total at the end. I was able to do a function that pulls the values from the pages attribute, now what would I have to use in order to add those values.

        var library = {
        
        book: 'A',
        pages: 1,
        next: {
            book: 'B',
            pages: 2,
            next: {
                book: 'C',
                pages: 3,
                next: null
            } //end of book c
        } //end of book b
        
    } //end of library
    
    function getPageCount(list) { //start of function
         var p = []
         if(list.next) p = p.concat(getPageCount(list.next));
        p.push(list.pages)
        return p
    } //end of function getPageCount
    
    console.log(getPageCount(library))

So this is what I have, running it will output [ 3, 2, 1] in console log, I now need to have it be something similar to [3 + 2 + 1 = 6]

Would array.reduce work here? Is it something simple and I just don't see it myself.

Thanks in advance!

Strife_x7x
  • 35
  • 5

1 Answers1

0

You may not need reduce , but use a recursive function to get the count of pages

var library = {
  book: "A",
  pages: 1,
  next: {
    book: "B",
    pages: 2,
    next: {
      book: "C",
      pages: 3,
      next: {
        book: "D",
        pages: 4,
        next: null
      }
    }
  }
};

function getPageCount(list, count) {
  //iterate the object
  for (let keys in list) {
    // add the number of page to a variable
    count += list.pages;
    if (
      // check if object has the property next and if it is a object
      list.hasOwnProperty("next") &&
      typeof list.next === "object" &&
      typeof list.next !== null
    ) {
      .. then call the same function and pass the object
      return getPageCount(list.next, count);
    } else {
      // otherwise add the number of pages to the variable
      return count += list.pages;
    }
  }
  return count
} //end of function getPageCount

console.log(getPageCount(library, 0));
brk
  • 48,835
  • 10
  • 56
  • 78