Search code examples
javascriptecmascript-6ecmascript-5

Having a conditon on every array element that's a part of an object


Just need to bring up an condition where I need to display a block based on the condition if its true or not

I have an array with following structure

const data = [
  { name: "item1" , values : [0,0,0,0,0]},
  { name: "item2" , values : [0,0,0,0,0]},
  { name: "item3" , values : [0,0,0,0,0]}
] // return false

const data = [
  { name: "item1" , values : [0,0,0,0,0]},
  { name: "item2" , values : [0,1,0,0,0]},
  { name: "item3" , values : [0,0,0,0,0]}
] // return true

Basically I need to have a check in such a way that if all entries inside "values" in each object is 0 then return false. If any of the entries inside "values" is other than 0 return true;

Have tried something like this. But does not seem like working

const isZero= (currentValue) => currentValue === 0;
console.log(data.every(isZero));

Solution

  • You could check the array and values.

    const check = array => array.some(({ values }) => values.some(Boolean));
    
    console.log(check([{ name: "item1", values: [0, 0, 0, 0, 0] }, { name: "item2", values: [0, 0, 0, 0, 0] }, { name: "item3", values: [0, 0, 0, 0, 0] }])); // return false
    console.log(check([{ name: "item1", values: [0, 0, 0, 0, 0] }, { name: "item2", values: [0, 1, 0, 0, 0] }, { name: "item3", values: [0, 0, 0, 0, 0] }])); // return true