1

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

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]
Ahsan Ajmal
  • 115
  • 7

4 Answers4

3

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);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
1

You can get a single array by just applying .flat() to your result.

A simpler version of your code:

const newArray = pa.map(e => e.sa ?? []).flat();
Fernando SA
  • 1,041
  • 1
  • 12
  • 20
1

Somewhat ironically, the approach with for loops will run a lot quicker than the other suggestions because it doesn't create intermediate copies of the array, and is subjectively just as readable.

for (let i = 0, sa; i < pa.length; i++)
  if (sa = pa[i].sa)
    for (let j = 0; j < sa.length; j++)
      newArray.push(sa[j]);
Tony B
  • 159
  • 6
0

Not sharing an optimized answer as few answers are already their. Just using your approach correctly so that you know how your logic can be used.

let output = [];
let k = pa.map(item => {
    if (item.sa) {
        output = [...output, ...item.sa];
    }
})