Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript includes to check for multiple values existance [duplicate]

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 ?

like image 218
user3019647 Avatar asked Jul 08 '26 13:07

user3019647


1 Answers

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)
like image 159
epascarello Avatar answered Jul 11 '26 03:07

epascarello



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!