Javascript 检查数组是否有来自另一个数组的元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/49218387/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Check if array has element(s) from another array
提问by Vikram S
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?
我有两个数组A = [0,1,2]和B = [2,1,0]. 如何检查A中的数字是否存在于B中?
回答by Pranav C Balan
NOTE: includesis not ES6, but ES2016Mozilla docs. This will break if you transpile ES6 only.
注意:includes不是 ES6,而是 ES2016 Mozilla 文档。如果您只转译 ES6,这会中断。
You can use Array#everymethod(to iterate and check all element passes the callback function) with Array#includesmethod(to check number present in B).
您可以使用Array#every方法(迭代并检查所有元素通过回调函数)和Array#includes方法(检查 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)));
要检查第二个数组中存在的单个元素,请执行以下操作:
A[0].includes(e)
//^---index
Or using Array#indexOfmethod, for older browser.
或使用Array#indexOf方法,适用于较旧的浏览器。
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#somemethod(to iterate and check at least one element passes the callback function).
或者,如果您想检查第二个数组中存在的至少一个元素,那么您需要使用Array#some方法(迭代并检查至少一个元素通过回调函数)。
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)));
回答by Kiren James
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.
这是我用来比较两个数组的自定义函数。如果数组元素相似则返回真,如果不同则返回假。注意:如果存在重复元素,则如果数组相等(array.len && array.val),则不返回 true。
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));
}
回答by Right2Drive
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
希望这对某人有所帮助:D

