How To Check If An Array Is The Same As Another Array In Javascript?
In this tutorial we are learn How do you check if an array contains element from another array Javascript?. I found this short and sweet syntax to match all or some elements between two arrays. Or Does item exist in array?
We Use some operator
and include operator
Very easy to use this tutorial we learn
The simplest and fastest way to check if an item is present in an array is by using the some and include operator See below:
For example
Ex. 1 - OR operator
find if any of array2 elements exists in array1. This will return as soon as there is a first match as some method breaks when function returns TRUE
let array1 = ['a', 'b', 'c', 'd', 'e'], array2 = ['a', 'b']; console.log(array2.some(ele => array1.includes(ele)));
Return: True
Ex. 2 - AND operator
find if all of array2 elements exists in array1. This will return as soon as there is a no first match as some method breaks when function returns TRUE
let array1 = ['a', 'b', 'c', 'd', 'e'], array2 = ['a', 'x']; console.log(!array2.some(ele => !array1.includes(ele)));
Return: False
I hope it can help you...
Leave a Reply