-2

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

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
Ae Leung
  • 300
  • 1
  • 12

1 Answers1

0

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.
protob
  • 3,317
  • 1
  • 8
  • 19