21

Is it possible to check if an array

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

Exists in another array

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

I want to check if all entries in array A exists in B

RPichioli
  • 3,085
  • 2
  • 24
  • 29
Leonel Matias Domingos
  • 1,665
  • 5
  • 24
  • 48

2 Answers2

37

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>

Just use _.difference

Steeve Pitis
  • 3,907
  • 1
  • 17
  • 24
9

You can use the intersection of the 2 arrays, and then compare to the original.

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));
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.16.2/lodash.js"></script>
Keith
  • 18,130
  • 2
  • 23
  • 36