2
const colors = ["black", "red", "pink", ];

this is colors array.I can check if one of the values is present in colors array. For e.g. here, I want to check if red is present in colors array. I use below code.

Const IsRedExist = colors.includes("red"); //returns true

So I want a flag to know if red or white or blue exists in colors array. How do I achieve that ? Any suggestions on this ?

2
  • 2
    another array with some or every Commented Jan 23, 2020 at 0:31
  • What do you mean by "want a flag"? Commented Jan 23, 2020 at 0:32

1 Answer 1

8

So you some and every with another array. Solution depends on what you actually need.

const colors = ["black", "red", "pink" ]

const checkFor = ["red", "white"]

const hasAll = checkFor.every(color => colors.includes(color))
const hasSome = checkFor.some(color => colors.includes(color))
const included = checkFor.filter(color => colors.includes(color))
const excluded = checkFor.filter(color => !colors.includes(color))
const checks = checkFor.reduce((obj, color) => ({[color]: colors.includes(color), ...obj}), {})

console.log('hasAll', hasAll)
console.log('hasSome', hasSome)
console.log('included', included)
console.log('excluded', excluded)
console.log('checks', checks, checks.red)

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.