2

How to merge multiple arrays in foreach loop. I'm trying to merge all 3 imageData arrays in one single array. Please tell if I missed anything from following method.

  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() {
    imageArray.forEach((element) => {
      const 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]
    });
  }
6
  • 1
    imageArray.reduce((p, c) => p.concat(c.imageData), []);, readable O(n²) solution for not overly large datasets. Commented Mar 8, 2021 at 17:19
  • 1
    You're redefining imageCollection in every loop. Commented Mar 8, 2021 at 17:20
  • 1
    you're looking for flatMap Commented Mar 8, 2021 at 17:28
  • 2
    Ngl even though it was not ES6 only (flatMap came 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. Commented Mar 8, 2021 at 17:28
  • I certainly didn't mean to have @Barmar delete his answer; I actually upvoted it. I think that people are too quick to tag things with ES versions. Unless you're asking a question about the version, or want answers to only use a specific version, there's no reason to tag a question with a version. Commented Mar 8, 2021 at 17:36

4 Answers 4

6

You declare the new imageCollection inside the loop.. Thus you create a new array each iteration...

Do it outside and use imageCollection.push(...element.imageData) inside forEach loop

Sign up to request clarification or add additional context in comments.

1 Comment

right sorry forgot the spread operator. Edited answere
5

Your array needs to be outside the forEach loop so it is accessible after the forEach is completed.

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']
  }
];

const processImage = function (imageArray) {
  const imageCollection = [];
  imageArray.forEach(element => {
    imageCollection.push(...element.imageData);
  });
  return imageCollection;
};

Expected result for processImage(imageArray)

[
  'https://via.placeholder.com/50',
  'https://via.placeholder.com/60',
  'https://via.placeholder.com/100',
  'https://via.placeholder.com/150'
]

Comments

1

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();

Comments

0

try this,foreach in the object imageData, and saving each value in an array using another Foreach.

    let newImageData = []

    imageArray.forEach((data)=>{

       const imageDataArray = data.imageData
       imageDataArray.forEach(link => {
        newImageData.push(link)
       });
      

  })
  
  const NewImageArray = {imageData:newImageData}
  console.log(NewImageArray)

2 Comments

Why use both map and forEach when the task can be accomplished with one of them? Additionally you did not define a return statement in your map. This will yield an error.
i was mapping without create a new object with the return, but u are right, better a simple foreach instead. is a aproach, i think is most readable

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.