skip to Main Content

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]

4

Answers


  1. 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);
    Login or Signup to reply.
  2. 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();
    
    Login or Signup to reply.
  3. 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];
        }
    })
    
    Login or Signup to reply.
  4. 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]);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search