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
You could take a flat mapping with a destructuring with optional array.
You can get a single array by just applying
.flat()
to your result.A simpler version of your code:
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.
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.