25

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,245
  • 2
  • 25
  • 29
Leonel Matias Domingos
  • 1,922
  • 5
  • 29
  • 53

3 Answers3

45

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
  • 4,283
  • 1
  • 21
  • 24
10

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
  • 22,005
  • 2
  • 27
  • 44
5

You don't need lodash in this case. Here's one liner with vanilla JS.

A.every(i => B.includes(i))
Yan Takushevich
  • 1,843
  • 2
  • 18
  • 23
  • Elegant, thanks for sharing. The OP requests a solution using Lodash, so technically this doesn't fit the requirement, but this is an elegant solution that removes the requirement to use Lodash (for the better). – Brock Klein Jan 19 '23 at 12:25