Bogdan
Bogdan

Reputation: 789

check if array includes value or includes another value

const isIncluded = ["1","2"]
        .includes("1") || ["1","2"]
        .includes("2") ;

how can I reformat this monstrosity in a more elegant way

Upvotes: 0

Views: 40

Answers (2)

FXX058
FXX058

Reputation: 11

You need something like this?

const checkIncluded = (arr1, arr2) => arr1.some(item => arr2.includes(item));

If any item from arr1 is inside arr2 returns true.

Example:

const isIncluded1 = checkIncluded(["1", "2"], ["1","2"]) // true
const isIncluded2 = checkIncluded(["1", "2"], ["1"]) // true
const isIncluded3 = checkIncluded(["1", "2"], ["2"]) // true
const isIncluded4 = checkIncluded(["1", "2"], ["3", "5"]) // false

Upvotes: 1

Nina Scholz
Nina Scholz

Reputation: 386570

For checking an array with another array, you could iterate one array and check the value with includes.

array.some(v => isIncluded.includes(v))

Upvotes: 1

Related Questions