使用lodash检查另一个数组中是否存在数组

时间:2016-10-03 13:40:12

标签: javascript arrays lodash

是否可以检查是否有数组

A=[
  "EMPRESA",
  "CD_MAQ",
  "DT_INI_MAQ"
]

存在另一个数组

B=[
  "EMPRESA",
  "CD_MAQ",
  "DT_INI_MAQ",
  "CD_WKC",
  "DT_INI_WKC"
]

我想检查数组A中的所有条目是否都存在于B

2 个答案:

答案 0 :(得分:6)



var A=[
  "EMPRESA",
  "CD_MAQ",
  "DT_INI_MAQ"
];

var B=[
  "EMPRESA",
  "CD_MAQ",
  "DT_INI_MAQ",
  "CD_WKC",
  "DT_INI_WKC"
];

if ( _.difference(A,B).length === 0){
  // all A entries are into B
}

<script src="https://cdn.jsdelivr.net/lodash/4.16.2/lodash.min.js"></script>
&#13;
&#13;
&#13;

只需使用_.difference

即可

答案 1 :(得分:4)

您可以使用2个数组的交集,然后与原始数组进行比较。

&#13;
&#13;
var A=[
  "EMPRESA",
  "CD_MAQ",
  "DT_INI_MAQ"
];

var B=[
  "EMPRESA",
  "CD_MAQ",
  "DT_INI_MAQ",
  "CD_WKC",
  "DT_INI_WKC"
];

console.log(_.isEqual(_.intersection(B,A), A));
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.16.2/lodash.js"></script>
&#13;
&#13;
&#13;