I have a JSON array, which looks as follows.
[
{
id: 1,
name: 'Alex',
activity: [
{
id: 'A1',
status: true
},
{
id: 'A2',
status: true
},
{
id: 'A3',
status: false
}
]
},
{
id: 2,
name: 'John',
activity: [
{
id: 'A6',
status: true
},
{
id: 'A8',
status: false
},
{
id: 'A7',
status: false
}
]
}
]
I want to get an array of activity id whose status should be true.I can achieve this with nester for
or forEach
loop. But here I am looking to achieve with the help of array functions like filter
, map
, and some
.
I have already tried with the following.
let newArr=arr.filter(a=> a.activity.filter(b=> b.status).map(c=> c.id))
But I didn't get the correct answer Expected output
['A1','A2','A6']
CodePudding user response:
function filter_activity(activities) {
return activities
&& activities.length
&& activities.map(x => x.activity)
.flat().filter(activity => activity.status)
.map(x => x.id) || [];
}
Illustration
function filter_activity(activities) {
return activities &&
activities.length &&
activities.map(x => x.activity)
.flat().filter(activity => activity.status)
.map(x => x.id) || [];
}
const input = [{
id: 1,
name: 'Alex',
activity: [{
id: 'A1',
status: true
},
{
id: 'A2',
status: true
},
{
id: 'A3',
status: false
}
]
},
{
id: 2,
name: 'John',
activity: [{
id: 'A6',
status: true
},
{
id: 'A8',
status: false
},
{
id: 'A7',
status: false
}
]
}
];
console.log(filter_activity(input));
WYSIWYG
=> WHAT YOU SHOW IS WHAT YOU GET
CodePudding user response:
let arr = json.flatMap(e => e.activity.filter(el => el.status).map(el => el.id))
CodePudding user response:
let newArr=arr.map(x => x.activity)
.reduce((acc, val) => acc.concat(val), [])
.filter((activity:any) => activity.status)
.map((x:any) => x.id) || [];
I got error when using flat()
and flatMap()
.So, I have used reduce()
.