Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
92
rated 0 times [  95] [ 3]  / answers: 1 / hits: 22408  / 7 Years ago, wed, september 20, 2017, 12:00:00

In an array of objects I need to find a value -- where key is activity : However the activity key can be deeply nested in the array like so:



const activityItems = [
{
name: 'Sunday',
items: [
{
name: 'Gym',
activity: 'weights',
},
],
},
{
name: 'Monday',
items: [
{
name: 'Track',
activity: 'race',
},
{
name: 'Work',
activity: 'meeting',
},
{
name: 'Swim',
items: [
{
name: 'Beach',
activity: 'scuba diving',
},
{
name: 'Pool',
activity: 'back stroke',
},
],
},
],
},
{} ...
{} ...
];


So I wrote a recursive algorithm to find out if a certain activity is in the array:



let match = false;
const findMatchRecursion = (activity, activityItems) => {
for (let i = 0; i < activityItems.length; i += 1) {
if (activityItems[i].activity === activity) {
match = true;
break;
}

if (activityItems[i].items) {
findMatchRecursion(activity, activityItems[i].items);
}
}

return match;
};


Is there an ES6 way of determining if an activity exists in an array like this?



I tried something like this:



const findMatch(activity, activityItems) {
let obj = activityItems.find(o => o.items.activity === activity);
return obj;
}


But this won't work with deeply nested activities.



Thanks


More From » arrays

 Answers
21

You can use some() method and recursion to find if activity exists on any level and return true/false as result.





const activityItems = [{name:Sunday,items:[{name:Gym,activity:weights}]},{name:Monday,items:[{name:Track,activity:race},{name:Work,activity:meeting},{name:Swim,items:[{name:Beach,activity:scuba diving},{name:Pool,activity:back stroke}]}]}]

let findDeep = function(data, activity) {
return data.some(function(e) {
if(e.activity == activity) return true;
else if(e.items) return findDeep(e.items, activity)
})
}

console.log(findDeep(activityItems, 'scuba diving'))




[#56433] Sunday, September 17, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
allanw

Total Points: 421
Total Questions: 132
Total Answers: 102

Location: Trinidad and Tobago
Member since Fri, May 8, 2020
4 Years ago
;