[SOLVED] Array iteration inside array of objects

Issue

I need to write a function that will go through all array objects and check wether at least one object has inner array where all objects have boolean value set to true. Please see code examples for better understanding.

Example 1

const array = [
  {
    id: 1,
    innerArray: [
      { innerId: 1, clicked: false },
      { innerId: 2, clicked: false },
    ],
  },
  {
    id: 2,
    innerArray: [
      { innerId: 1, clicked: true },
      { innerId: 2, clicked: false },
    ],
  },
  {
    id: 3,
    innerArray: [
      { innerId: 1, clicked: true },
      { innerId: 2, clicked: true }, 
    ],
  },
];

functionToBeCreated(array); // Output: true - because item with id 3 has innerArray where all items have "clicked: true".

Example 2

const array = [
  {
    id: 1,
    innerArray: [
      { innerId: 1, clicked: false },
      { innerId: 2, clicked: false },
    ],
  },
  {
    id: 2,
    innerArray: [
      { innerId: 1, clicked: true },
      { innerId: 2, clicked: false },
    ],
  },
  {
    id: 3,
    innerArray: [
      { innerId: 1, clicked: false },
      { innerId: 2, clicked: true }, 
    ],
  },
];

functionToBeCreated(array); // Output: false - because no item has innerArray where all items have "clicked: true".

Do you have maybe any ideas how it ca be achieved?

Solution

this way…

const ToBeCreated = arr =>
   arr.some( el => el.innerArray.every(z => z.clicked));

const arrayTRUE = 
  [ { id: 1, innerArray: 
      [ { innerId: 1, clicked: false } 
      , { innerId: 2, clicked: false }
      ] } 
  , { id: 2, innerArray: 
      [ { innerId: 1, clicked: true  } 
      , { innerId: 2, clicked: false } 
    ] } 
  , { id: 3, innerArray: 
      [ { innerId: 1, clicked: true } 
      , { innerId: 2, clicked: true } 
  ] } ] 

const arrayFALSE = 
  [ { id: 1, innerArray: 
      [ { innerId: 1, clicked: false } 
      , { innerId: 2, clicked: false }
      ] } 
  , { id: 2, innerArray: 
      [ { innerId: 1, clicked: true  } 
      , { innerId: 2, clicked: false } 
    ] } 
  , { id: 3, innerArray: 
      [ { innerId: 1, clicked: false } 
      , { innerId: 2, clicked: true  } 
  ] } ] 

// test 
console.log( ToBeCreated(arrayTRUE ) ) 
console.log( ToBeCreated(arrayFALSE) ) 

Answered By – Mister Jojo

Answer Checked By – Dawn Plyler (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published.