1
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 ?

Dai
  • 141,631
  • 28
  • 261
  • 374
user3019647
  • 133
  • 3
  • 13

1 Answers1

6

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)
epascarello
  • 204,599
  • 20
  • 195
  • 236