Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if array exists in another array with lodash

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

like image 400
Leonel Matias Domingos Avatar asked Oct 03 '16 13:10

Leonel Matias Domingos


People also ask

How do you check if an array exists in another array?

You can use the includes() method in JavaScript to check if an item exists in an array. You can also use it to check if a substring exists within a string. It returns true if the item is found in the array/string and false if the item doesn't exist.

How do you find an array within an array?

Use filter if you want to find all items in an array that meet a specific condition. Use find if you want to check if that at least one item meets a specific condition. Use includes if you want to check if an array contains a particular value. Use indexOf if you want to find the index of a particular item in an array.

How do I check if an object is in Lodash?

Lodash helps in working with arrays, strings, objects, numbers, etc. The _. isObject() method is used to find whether the given value is an object or not. It returns a Boolean value True if the given value parameter is an object and returns False otherwise.


2 Answers

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

like image 134
Steeve Pitis Avatar answered Sep 25 '22 14:09

Steeve Pitis


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>
like image 40
Keith Avatar answered Sep 23 '22 14:09

Keith