Home > Mobile >  Search through items and find which meets the criteria and give back Boolean
Search through items and find which meets the criteria and give back Boolean

Time:11-27

We have array with objects:

 let store =  [
        {
          id: 1,
          name: "store1",
          items: {
            pen: 0,
            apple: 1,
            chocolate: 0
          }
        },
        {
          id: 2,
          name: "store2",
          items: {
            pen: 0,
            apple: 0,
            chocolate: 0
          }
        },
        {
          id: 3,
          name: "store3",
          items: {
            pen: 0,
            apple: 1,
            chocolate: 1
          }
        },
      ]

and the criteria is: ["apple", "chocolate"].

We have to find the objects where meets the criteria.lenght > 0 and give back a boolean true/false

This is how I tried

store.filter(store => criteria.forEach(i => store.items[i] > 0))

CodePudding user response:

You could filter by checking all criteria with Array#every.

const
    stores =  [{ id: 1, name: "store1", items: { pen: 0, apple: 1, chocolate: 0 } }, { id: 2, name: "store2", items: { pen: 0, apple: 0, chocolate: 0 } }, { id: 3, name: "store3", items: { pen: 0, apple: 1, chocolate: 1 } }],
    criteria = ["apple", "chocolate"],
    result = stores.filter(store => 
        criteria.every(criterion => store.items[criterion] > 0)
    );

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

If you want all stores if at least on criterion is true, take Array#some

const
    stores =  [{ id: 1, name: "store1", items: { pen: 0, apple: 1, chocolate: 0 } }, { id: 2, name: "store2", items: { pen: 0, apple: 0, chocolate: 0 } }, { id: 3, name: "store3", items: { pen: 0, apple: 1, chocolate: 1 } }],
    criteria = ["apple", "chocolate"],
    result = stores.filter(store => 
        criteria.some(criterion => store.items[criterion] > 0)
    );

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

  • Related