Fredrik
Fredrik

Reputation: 3302

Check if array exists in array using lodash

How do I verify if a child array exists in its parent? I have tried _.includes, _.find and _.findIndex without any luck.

let arr = [[1],[2],[3]];
let el = [1];

_.includes(arr, el)   // false
_.find(arr, el)       // undefined
_.findIndex(arr, el)  // -1

To clarify, the el is an array that contains n amount of integers, whilst arr is an array that contains n amount of arrays.

Edit: added JSBIN: https://jsbin.com/tequcoloro/edit?js,console

Upvotes: 0

Views: 1537

Answers (3)

Rob M.
Rob M.

Reputation: 36541

If your arrays are ordered you don't have to walk each of them:

let arr = [[1],[2],[3]];
let el = [1];

console.log(
  arr.some(arr => arr.toString() === el.toString())
)

Upvotes: 2

apokryfos
apokryfos

Reputation: 40730

Since Lodash is your weapon of choice here you can do:

_.findIndex(arr, function (v) { return _.isEqual(v, el); }); // 0

Upvotes: 3

Dekel
Dekel

Reputation: 62676

You will have to walk over the array and compare it's elements.

You can use the _.isEqual function to do so:

let arr = [[1],[2],[3]];
let el = [1];

console.log(arr.filter((e) => _.isEqual(e, el)))
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.min.js"></script>

Upvotes: 3

Related Questions