-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
1
  • 1
    you have typos: "cosnt" Commented Mar 2, 2023 at 8:21

1 Answer 1

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.
Sign up to request clarification or add additional context in comments.

5 Comments

sorry, my bad, Actually i want to say if part of it is correct, then i should also pass it. is it possible to do it?
@AeLeung just use some instead of every
@pilchard, i added your comment to the answer.
That's great, but you should actually vote to close as duplicate
Yeah, this question had to be common, i saw your comment with link.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.