Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to filter an array of object inside an array of objects based on an array and also remove properties of that object?

let array1= [
    { "id": 100, name: "A", "details": [{"year": "2012"},{"data": "Test1"}]},
    { "id": 101, name: "B", "details": [{"year": "2013"},{"data": "Test2"}]},
    { "id": 102, name: "C", "details": [{"year": "2014"},{"data": "Test3"}]}
];

const array2= ['2012'];

Result I wanted

{ "id": 100, name: "A", "details": [{"year": "2012"}]}

I know i can filter the array with this code

array1.filter(o => 
  o.details.some(p=> {
    return array2.includes(p.year)
  })
)

But is there a way to remove the objects as well.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

We can reduce to avoid multiple steps

This reduce filters and deletes part of the details array

let array1 = [
    { "id": 100, name: "A", "details": [{"year": "2012"},{"data": "Test1"}]},
    { "id": 101, name: "B", "details": [{"year": "2013"},{"data": "Test2"}]},
    { "id": 102, name: "C", "details": [{"year": "2014"},{"data": "Test3"}]}
];

const array2 = ['2012'];

let array3 = array1.reduce((acc, {id,name,details}) => {
  if (array2.includes(details[0].year)) {
    acc.push({ id, name, details: details[0] })
  }
  return acc
}, [])

console.log(array3)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading