0

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

1
  • 2
    [1] is not equal to another [1] because they're really different objects with the same content Commented Apr 30, 2018 at 22:52

3 Answers 3

3

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>

Sign up to request clarification or add additional context in comments.

Comments

3

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

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

Comments

2

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())
)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.