Sometimes, we want to check whether an array exists in an array of arrays with JavaScript.
In this article, we’ll look at how to check whether an array exists in an array of arrays with JavaScript.
Check Whether an Array Exists in an Array of Arrays with JavaScript
To check whether an array exists in an array of arrays with JavaScript, we can stringify both arrays with the JSON.stringify
method.
Then we can use the JavaScript string indexOf
method to check whether an array exists in an array of arrays by checking the stringified versions of them.
For instance, we write:
const a = [
[1, 2],
[3, 4]
];
const b = [1, 2];
const aStr = JSON.stringify(a);
const bStr = JSON.stringify(b);
const exist = aStr.indexOf(bStr) !== -1;
console.log(exist)
to define and a
and b
arrays.
Then we call JSON.stringify
with a
and b
to return the string versions of the array.
Next, we call aStr.indexOf
with bstr
to check if bStr
is in aStr
.
And if indexOf
returns anything other than -1, then we know bStr
is in aStr
.
Therefore, exist
is true
according to the console log.
Conclusion
To check whether an array exists in an array of arrays with JavaScript, we can stringify both arrays with the JSON.stringify
method.
Then we can use the JavaScript string indexOf
method to check whether an array exists in an array of arrays by checking the stringified versions of them.