JavaScript
x
8
1
let array1= [
2
{ "id": 100, name: "A", "details": [{"year": "2012"},{"data": "Test1"}]},
3
{ "id": 101, name: "B", "details": [{"year": "2013"},{"data": "Test2"}]},
4
{ "id": 102, name: "C", "details": [{"year": "2014"},{"data": "Test3"}]}
5
];
6
7
const array2= ['2012'];
8
Result I wanted
JavaScript
1
2
1
{ "id": 100, name: "A", "details": [{"year": "2012"}]}
2
I know i can filter the array with this code
JavaScript
1
6
1
array1.filter(o =>
2
o.details.some(p=> {
3
return array2.includes(p.year)
4
})
5
)
6
But is there a way to remove the objects as well.
Advertisement
Answer
We can reduce to avoid multiple steps
This reduce filters and deletes part of the details array
JavaScript
1
16
16
1
let array1 = [
2
{ "id": 100, name: "A", "details": [{"year": "2012"},{"data": "Test1"}]},
3
{ "id": 101, name: "B", "details": [{"year": "2013"},{"data": "Test2"}]},
4
{ "id": 102, name: "C", "details": [{"year": "2014"},{"data": "Test3"}]}
5
];
6
7
const array2 = ['2012'];
8
9
let array3 = array1.reduce((acc, {id,name,details}) => {
10
if (array2.includes(details[0].year)) {
11
acc.push({ id, name, details: details[0] })
12
}
13
return acc
14
}, [])
15
16
console.log(array3)