Reputation: 353
If I have an array of arrays looks like following,
const ar = [
[2,6,7,9],
[3,2,4,6],
[7,8,9,10]
];
what will be a smart way to return the first item, that contains a number 3.
want to get an array [3,2,4,6]
.
Thanks
Upvotes: 0
Views: 109
Reputation: 6888
something like
ar.find(innerAr -> innerAr.includes(3))
should work. I would encapsulate the solution along these lines:
const findInnerArrayWith = val => arr =>
arr.find(innerAr -> innerAr.includes(val))
in use this would be:
const findInnerArrayWith3 = findInnerArrayWith(3)
const inner = findInnerArrayWith(ar)
or if you want to run multiple queries against the array (holding the array constant and varying the object to find) I might flip the parameters
const findIn = arr => val =>
arr.find(innerAr -> innerAr.includes(val))
const findInAr = findIn(ar)
const inner = findInAr(3)
maybe thats a bit beyond the scope of the question - but the order of the parameters opens up some interesting approaches to structuring your code.
references
Upvotes: 1
Reputation: 1003
This is an example how you can do it with array find and indexOf. Simply put, array.find looks for the first element matches an condition. And the condition is where the array.indexOf comes in to check the membership of target in an array.
const ar = [
[2,6,7,9],
[3,2,4,6],
[7,8,9,10]
];
const target = 3; // the target number you are looking
let result = ar.find( a => a.indexOf(3) !== -1);
Upvotes: 1