简体   繁体   中英

Checking if two dimensional array contains one dimensional

I have two arrays - one dimensional and one two dimensional.

a = [[1,1],[2,2]];
b = [1,1];

I want to check if 'a' has element like 'b'. We see that 'a' constains [1,1] and b is [1,1] so lets check it:

a.indexOf(b)

it returns -1 , 'a' doesn't contain 'b' and I don't get it.

Cheers

indexOf compares using strict equality ( === ). Your elements would have to be the exact same object.

so

var a = [1,1];

var b = [a,[1,2]];

b.indexOf(a)// 0

because a === a

but

b.indexOf([1,1])// -1

because [1,1] is a different object than a so they're not strictly equal.

MDN Docs

To do what you want to do you'll need to do something more involved. You can loop over the values and use something like whats in this question's answers to do the comparison

indexOf returns -1 if it does not find a match in the array . Your array a does not contain element b .

EDIT:

To clarify on what @JonathanLonowski said, the reason there is not a match is because you are doing a strict comparison, comparing the references, not the values.

<Array>.some method tests whether at least one array in the multi-dimensional array passes the test implemented by the provided function.

<Array>.every method tests whether all array items in the array pass the test implemented by the provided function.

These two methods combined make it possible to check if all the items of an array in the multidimensional one are worth those of that sought.

 const checkArray = (arrays, array) => arrays.some(a => { return (a.length > array.length ? a : array).every((_, i) => a[i] === array[i]); }); const arrays = [[0, 1], [2, 2], [0, 3, 2, 1]]; [ [0, 1], // true [2, 2], // true [0, 3, 2, 1], // true [1, 0, 3, 2, 1], // false [2, 2, 1], // false [0, 0], // false [1, 2], // false [0, 1, 2] // false ].forEach(array => { console.log(checkArray(arrays, array)); });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM