I have two arrays A = [0,1,2] and B = [2,1,0]. How to check if a number in A is present in B?
5 Answers
NOTE: includes is not ES6, but ES2016 Mozilla docs. This will break if you transpile ES6 only.
You can use Array#every method(to iterate and check all element passes the callback function) with Array#includes method(to check number present in B).
A.every( e => B.includes(e) )
const A = [0, 1, 2],
B = [2, 1, 0],
C=[2, 1];
console.log(A.every(e => B.includes(e)));
console.log(A.every(e => C.includes(e)));
console.log(C.every(e => B.includes(e)));
To check a single element present in the second array do:
A[0].includes(e)
//^---index
Or using Array#indexOf method, for older browser.
A[0].indexOf(e) > -1
Or in case you want to check at least one element present in the second array then you need to use Array#some method(to iterate and check at least one element passes the callback function).
A.some(e => B.includes(e) )
const A = [0, 1, 2],
B = [2, 1, 0],
C=[2, 1],D=[4];
console.log(A.some(e => B.includes(e)));
console.log(A.some(e => C.includes(e)));
console.log(C.some(e => B.includes(e)));
console.log(C.some(e => D.includes(e)));
4 Comments
A = [0], B = [0,1,2]Here's a self defined function I use to compare two arrays. Returns true if array elements are similar and false if different. Note: Does not return true if arrays are equal (array.len && array.val) if duplicate elements exist.
var first = [1,2,3];
var second = [1,2,3];
var third = [3,2,1];
var fourth = [1,3];
var fifth = [0,1,2,3,4];
console.log(compareArrays(first, second));
console.log(compareArrays(first, third));
console.log(compareArrays(first, fourth));
console.log(compareArrays(first, fifth));
function compareArrays(first, second){
//write type error
return first.every((e)=> second.includes(e)) && second.every((e)=> first.includes(e));
}
2 Comments
If the intent is to actually compare the array, the following will also account for duplicates
const arrEq = (a, b) => {
if (a.length !== b.length) {
return false
}
const aSorted = a.sort()
const bSorted = b.sort()
return aSorted
.map((val, i) => bSorted[i] === val)
.every(isSame => isSame)
}
Hope this helps someone :D
Comments
If you just need to know whether A and B has same entries, simply
JSON.stringify(A.concat().sort()) === JSON.stringify(B.concat().sort())
Note:
If there are null and undefined in each array, it will be true. Because JSON#stringify converts undefined to null.
JSON.stringify([null].concat().sort()) === JSON.stringify([undefined].concat().sort())
// true
Comments
A.length === B.length && A.every(e => B.includes(e))
A.every( e => B.includes(e) )A.some(e => B.includes(e))if you meant "any number of A present in B".