Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

This is how I tried

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

>Solution :

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; }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading