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

How do I determine whether an array contains the whole/part of array of string?

How do I determine whether an array contains a particular value in string or consist the whole array of string ?

For example

const list = ['appple','orange','burger','pizza']

by includes, I can check if particular value exist in list

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

But how can I check with a list of string

like

const listToCheck = ['appple','orange']

list.includes(listToCheck)  <= gives me true


const listToCheck = ['appple','orange','pineapple']

list.includes(listToCheck)  <= gives me true

>Solution :

You can use every() or some() with includes(), depending on your needs:

const list = ['apple', 'orange', 'burger', 'pizza'];

const listToCheck1 = ['apple', 'orange'];
const listToCheck2 = ['apple', 'orange', 'pineapple'];
const listToCheck3 = ['pineapple', 'mango'];

const every1 = listToCheck1.every(item => list.includes(item)); 
const every2 = listToCheck2.every(item => list.includes(item)); 
console.log("every1",every1)
console.log("every2",every2)

const some1 = listToCheck1.some(item => list.includes(item)); 
const some2 = listToCheck2.some(item => list.includes(item)); 
const some3 = listToCheck3.some(item => list.includes(item)); 
console.log("some1",some1);
console.log("some2",some2);
console.log("some3",some3);
  • some() is like an union. It checks if any element in one array exists in the other array
  • every() is like an intersection. It checks if all elements in one array are also in the other array.
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