Aria
Aria

Reputation: 393

Filter nested arrays using .filter() function

I have an array that looks like this:

const data = [
 {"total": 24,"items":[{"id":1,"name":"foo1", "items": [{"label": "TEST", "total": 50}, {"label": "TEST2", "total": 50}]}]},
{"total": 25,"items":[{"id":2,"name":"foo2", "items": [{"label": "FOO", "total": 60}, {"label": "ANOTHER2", "total": 50}]}]},
{"total": 26,"items":[{"id":3,"name":"foo3", "items": [{"label": "BAR", "total": 70}, {"label": "LAST2", "total": 50}]}]},
];

and I wanted to use the .filter() function in angular so when I pass in the string '2', it returns the object containing only the nested arrays which contains the string '2', in other words should return this:

[
 {"total": 24,"items":[{"id":1,"name":"foo1", "items": [{"label": "TEST2", "total": 50}]}]},
{"total": 25,"items":[{"id":2,"name":"foo2", "items": [{"label": "ANOTHER2", "total": 50}]}]},
{"total": 26,"items":[{"id":3,"name":"foo3", "items": [{"label": "LAST2", "total": 50}]}]},
];

I tried

let values = data.items.filter(d => d.items.forEach(c => c.label.toLowerCase().includes(searchText.toLowerCase())
}))

and it just returns an empty array,

I also tried

 let values = data.items.forEach(d => d.items.filter(c => c.label.toLowerCase().includes(searchText.toLowerCase())
})) 

and

let values = data.items.filter(d => d.items.every(c => c.label.toLowerCase().includes(searchText.toLowerCase())
}))

and both return undefined and an empty array.

what is the correct way to do this?

Upvotes: 0

Views: 99

Answers (1)

Donald Duck
Donald Duck

Reputation: 638

const data = [
 {"total": 24,"items":[{"id":1,"name":"foo1", "items": [{"label": "TEST", "total": 50}, {"label": "TEST2", "total": 50}]}]},
{"total": 25,"items":[{"id":2,"name":"foo2", "items": [{"label": "FOO", "total": 60}, {"label": "ANOTHER2", "total": 50}]}]},
{"total": 26,"items":[{"id":3,"name":"foo3", "items": [{"label": "BAR", "total": 70}, {"label": "LAST2", "total": 50}]}]},
];

let searchText='TEST'

let values =  JSON.parse(JSON.stringify(data)).map(d => {
d.items.map(i=> {
i.items = i.items.filter(c =>c.label.toLowerCase().includes(searchText.toLowerCase()));
return i;
})
return d;
})

console.log(values)

let values =  JSON.parse(JSON.stringify(data)).map(d => {
d.items.map(i=> {
i.items = i.items.filter(c =>c.label.toLowerCase().includes(searchText.toLowerCase()));
return i;
})
return d;
})

forEach doesn't return anything, map returns the array, where each element is replaced by the return value of from the function you pass to it.Also you weren't accessing deep enough, since your target array is at data[0].items[0].items, for example. I might have missed a parenthesis or bracket here

Upvotes: 2

Related Questions