[英]Determining if all elements in array A are present in array B
So this is the code: 所以这是代码:
var array_A = [1,2,4];
var array_B = [1,2,3,4];
I need a function that for the case above will print TRUE. 我需要一个在上述情况下将输出TRUE的函数。 Because
因为
1,2 and 4
are present in array_B. 存在于array_B中。
The function will print FALSE if the declaration is as following: 如果声明如下,该函数将显示FALSE:
var array_A = [1,2,4,5];
var array_B = [1,2,3,4];
Because 因为
"5"
is not present in array_B. 在array_B中不存在。
I guess this is quite easy to accomplish with lodash or underscore. 我猜这很容易用lodash或下划线完成。 But could not find exactly what I was looking for.
但是找不到我想要的东西。 Any hint?
有什么提示吗?
Use array every and indexOf: 使用每个数组和indexOf:
var array_A = [1,2,4]; var array_B = [1,2,3,4]; var result = array_A.every(el => array_B.indexOf(el) !== -1); console.log(result);
You could use Array#includes
with Array#forEach
. 您可以将
Array#includes
与Array#forEach
。
var array_A = [1, 2, 4], array_B = [1, 2, 3, 4], result = array_A.every(a => array_B.includes(a)); console.log(result);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.