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

Pull values from array to a new single array

I have an array like this:

pa: [{ 
  id: 1,
  sa: [ 1, 2, 3 ]
}, {
  id: 2,
  sa: [ 1, 2, 3 ]
}, {
  id: 3,
}]

Some of the objects contain an sa array and some don’t. I want to create a new array that contains all the numbers of sa in a new single array

I have tried this but it will add in multiple arrays

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

for (let i = 0; i < pa.length; i++) {
  if (pa[i].sa!== undefined && pa[i]?.sa) {
    f.push(p[i]?.sa?.map(a=> a.id));
  }
}

i want the final array to be

newArray = [1,2,3,1,2,3]

>Solution :

You could take a flat mapping with a destructuring with optional array.

const
    data = { pa: [{ id: 1, sa: [1, 2, 3] }, { id: 2, sa: [1, 2, 3] }, { id: 3 }] },
    result = data.pa.flatMap(({ sa = [] }) => sa);

console.log(result);
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