You can assign imageCollection outside of the forEach (but still inside of processImage()). Then in the redefinition of imageCollection inside of the forEach, spread the contents of each previous imageCollection array, followed by the contents of element.imageData. Like so:
//...
processImage() {
let imageCollection = [];
imageArray.forEach((element) => {
imageCollection = [...imageCollection, ...element.imageData];
//...
Full Code for Your Context
const imageArray = [
{
imageData: [
'https://via.placeholder.com/50',
'https://via.placeholder.com/60'
],
},
{
imageData: [
'https://via.placeholder.com/100'
],
},
{
imageData: [
'https://via.placeholder.com/150'
],
}
];
processImage() {
let imageCollection = [];
imageArray.forEach((element) => {
imageCollection = [...imageCollection, ...element.imageData];
console.log(imageCollection);
// Expected result
//['https://via.placeholder.com/50', 'https://via.placeholder.com/60', 'https://via.placeholder.com/100', https://via.placeholder.com/150]
});
console.log('ImageCollection',imageCollection);
}
Full Code for Running Outside of Your Context
const imageArray = [
{
imageData: [
'https://via.placeholder.com/50',
'https://via.placeholder.com/60'
],
},
{
imageData: [
'https://via.placeholder.com/100'
],
},
{
imageData: [
'https://via.placeholder.com/150'
],
}
];
function processImage() {
let imageCollection = [];
imageArray.forEach((element) => {
imageCollection = [...imageCollection, ...element.imageData];
console.log(imageCollection);
// Expected result
//['https://via.placeholder.com/50', 'https://via.placeholder.com/60', 'https://via.placeholder.com/100', https://via.placeholder.com/150]
});
console.log('ImageCollect',imageCollection);
}
processImage();
imageArray.reduce((p, c) => p.concat(c.imageData), []);, readable O(n²) solution for not overly large datasets.imageCollectionin every loop.flatMapcame later), i liked that solution the most, because it was very readable, and hopefully O(n) (i'd assume engines optimize that much). My glass ball tells me, that being overly specific on ES6 is not the intention anyways.