I have an object as follows:
const overall = {
mainData: {
id: 1,
group: 'grp0'
},
data: [
{
id: 2,
group: 'grp3'
},
{
id: 3,
group: 'grp3'
}
]
}
I want to do a combined check across both mainData and data.
Search for a particular grp in a them. For example searching for grp3.
If there is at least 2 grp3, return true, else return false.
In the above, result will be true cos there is 2 grp 3.
Another example where it will be true. two grp3.
const overall = {
mainData: {
id: 1,
group: 'grp3'
},
data: [
{
id: 2,
group: 'grp3'
}
]
}
An example where it will be false. Only 1 grp3
const overall = {
mainData: {
id: 1,
group: 'grp0'
},
data: [
{
id: 1,
group: 'grp1'
},
{
id: 2,
group: 'grp2'
},
{
id: 3,
group: 'grp3'
},
{
id: 4,
group: 'grp4'
}
]
}
How could I achieve this in a single flow of filters and maps?
Currently performing this which feels verbose.
const mainGroup = [overall.mainData];
const dataGroups = overall.data.filter(d => d.group);
const allGroups = [...mainGroup, ...dataGroups];
const isMorethanOneItem = allGroups.filter(item => item.group === 'grp3').length > 1;
>Solution :
Basedon your code, we can reduce it to one line
let contains = [overall.mainData,...overall.data].filter(d => d.group == key).length > 1
const overall = {
mainData: {
id: 1,
group: 'grp0'
},
data: [
{
id: 2,
group: 'grp3'
},
{
id: 3,
group: 'grp3'
}
]
}
let key ='grp3'
let result = [overall.mainData,...overall.data].filter(d => d.group == key).length > 1
console.log(result)