skip to Main Content

I am trying to access the key ‘children’ inside of these nested arrays listed below. I want a total count of how many children there are. I am rather new to coding and I’ve been trying some things out but have not been able to figure the problem. any help?

also, I want to use the reduce method to accomplish this task thanks!

const characters = [
  {
    name: 'Eddard',
    spouse: 'Catelyn',
    children: ['Robb', 'Sansa', 'Arya', 'Bran', 'Rickon'],
    house: 'Stark',
  },
  {
    name: 'Jon',
    spouse: 'Lysa',
    children: ['Robin'],
    house: 'Arryn',
  },
  {
    name: 'Cersei',
    spouse: 'Robert',
    children: ['Joffrey', 'Myrcella', 'Tommen'],
    house: 'Lannister',
  },
  {
    name: 'Daenarys',
    spouse: 'Khal Drogo',
    children: ['Drogon', 'Rhaegal', 'Viserion'],
    house: 'Targaryen',
  },
  {
    name: 'Mace',
    spouse: 'Alerie',
    children: ['Margaery', 'Loras'],
    house: 'Tyrell',
  },
  {
    name: 'Sansa',
    spouse: 'Tyrion',
    house: 'Stark',
  },
  {
    name: 'Jon',
    spouse: null,
    house: 'Snow',
  },
];

const countNumberOfChildren = (arr) => {
  const selectChildren = arr.reduce((acc, c)=>{
   console.log('this is c', c)
   console.log('this is acc', acc)
   acc + c.children.length()
   console.log('this is acc2', acc)

  return acc
  }, 0)
  console.log(selectChildren) 
};

countNumberOfChildren(characters)

2

Answers


  1. The issue is that acc + c.children.length() does not change the acc variable and that .length is not a function, it is a property. Also, so elements might not have a .children property.

    You can condense that entire .reduce() call into one line and use optional chaining and null coalescing to handle elements that don’t have a .children array like this:

    const characters=[{name:'Eddard',spouse:'Catelyn',children:['Robb','Sansa','Arya','Bran','Rickon'],house:'Stark'},{name:'Jon',spouse:'Lysa',children:['Robin'],house:'Arryn'},{name:'Cersei',spouse:'Robert',children:['Joffrey','Myrcella','Tommen'],house:'Lannister'},{name:'Daenarys',spouse:'Khal Drogo',children:['Drogon','Rhaegal','Viserion'],house:'Targaryen'},{name:'Mace',spouse:'Alerie',children:['Margaery','Loras'],house:'Tyrell'},{name:'Sansa',spouse:'Tyrion',house:'Stark'},{name:'Jon',spouse:null,house:'Snow'}];
    
    
    const numChildren = characters.reduce((acc, curr) => acc + (curr.children?.length ?? 0), 0);
    console.log(numChildren);
    Login or Signup to reply.
  2. Edit your countNumberOfChildren function to

    const countNumberOfChildren = (arr) => {
      const selectChildren = arr.reduce((acc, c) =>  acc + (c.children ? c.children.length : 0), 0);
      return selectChildren;    
    };
    

    Here, we are first checking whether a property named ‘children’ exists in the current element (c) or not. If it exist then add its length to acc else add 0.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search