How can you locate the first item that meets specific criteria within a nested array and halt the search once it is found?
In a one-dimensional array, this task can be accomplished with the Array.find function. But how would you tackle this in a two-dimensional array, or even better, in an n-dimensional array?
I am exploring a streamlined solution using ES6 and array functions like find, map, and reduce, rather than relying on traditional loops and variables to maintain state (see old-school approach below).
The data structure might resemble:
const data = [
{arr: [{val:6,name:'aaa'},{val:4,name:'bbb'},{val:8,name:'ccc'}]},
{arr: [{val:3,name:'mmm'},{val:5,name:'nnn'},{val:9,name:'ppp'},{val:5,name:'ooo'}]}
]
I am aiming for a method akin to array.find, including its predicate/testing function, but with the ability to delve deep and identify the first occurrence of val=5, for instance. Given the example data above, I anticipate retrieving the element named 'nnn' (not 'ooo') and terminating the process upon finding the initial match. Just like Array.find, my goal is to cease processing the remaining data after encountering a matching item.
An unexciting conventional technique involves utilizing a loop like so:
let found
// iterating through all entries in the outer array
for (const d of data) {
// searching for a matching item in the inner array.
// utilizing array.find ensures halting at the first match
const theItem = d.arr.find(item => {
return myPredicate(item)
})
// breaking out of the loop when a match is obtained
if (theItem) {
found = theItem
break
}
}
// returning the found item (may be undefined)
return found
A potential workaround could involve employ find() and some(), as shown in this response ES6 - Finding data in nested arrays. However, employing find on the external array results in obtaining the first item within the outer data array, whereas I require an element from the internal arr array.
const outer = data.find(d => {
return d.arr.some(item => {
return myPredicate(item)
})
})
Subsequently, I would have to revisit outer to pinpoint the item within outer.arr, similar to:
outer.arr.find(item => myPredicate(item))
This methodology seems inefficient since some(...) already identified the matching inner item!
I anticipated this task to be straightforward, yet for some reason, it has posed a challenge for me.
I also explored the traverse library (https://www.npmjs.com/package/traverse), although it appears more focused on traversing an entire tree instead of pausing and returning upon discovering a particular node.
Who’s up for a challenge? ;)