skip to Main Content

I have an array objects. Inside that i want to check all selected values are true or not. below code is not working. How to check in typescript or javascript.

  ngOnInit() {
let arr1 = [
  {
    name: 'test1',
    selected: true,
  },
  {
    name: 'test1',
    selected: true,
  },
  {
    name: 'test1',
    selected: true,
  },
];

let arr2 = [
  {
    name: 'test1',
    selected: true,
  },
  {
    name: 'test1',
    selected: true,
  },
  {
    name: 'test1',
    selected: false,
  },
];
console.log(this.checkallTrue(arr1));
console.log(this.checkallTrue(arr2));
   }

   checkallTrue(arr) {
     for (const n of arr) {
      if (n.selected == true) {
       return true;
      } else {
       return false;
      }
      }
     }

Demo: https://stackblitz.com/edit/github-7plax5-ydjwxc?file=src%2Fapp%2Fapp.component.ts

2

Answers


  1. Your code only looks at the first element of the array, and based on that either returns true or false. The loop will never get to the second element of the array. To fix this, only return true at the end of the loop, once you’ve confirmed that they all are ok.

    checkallTrue(arr) {
      for (const n of arr) {
        if (n.selected !== true) {
          return false;
        }
      }
      return true;
    }
    
    Login or Signup to reply.
  2. All you really need is Array#every() which checks if every item in your array matches a criteria.

    let arr1 = [
      {
        name: "test1",
        selected: true
      },
      {
        name: "test1",
        selected: true
      },
      {
        name: "test1",
        selected: true
      }
    ];
    let arr2 = [
      {
        name: 'test1',
        selected: true,
      },
      {
        name: 'test1',
        selected: true,
      },
      {
        name: 'test1',
        selected: false,
      },
    ];
    
    const allSelected = arr => arr.every(e => e.selected);
    
    console.log(allSelected(arr1));
    console.log(allSelected(arr2));
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search