How to concat two array in one with this data? JS

Viewed 81

I need to concat two arrays. First Array is an array of descriptions

4 Answers

Assuming the arrays are always of equal length... you can use the second argument passed to the callback function(which is the index of each element) for accessing the elements of the other array.

const description = ['One', 'Two', 'Three'];

const allPictures = ['url-1', 'url-2', 'url-3'];

const result = description.map((des, index) => ({
  url: allPictures[index],
  description: des
}));

console.log(result);

If you don't want to create an object when either of the arrays has falsy values:

const descriptions = ['One', '', 'Three', undefined];

const allPictures = ['url-1', 'url-2', null, ''];

const result = descriptions.reduce((acc,description, index) => {
  const url = allPictures[index];
  if(description && url) {
    acc.push({ description, url });
  }
  return acc;
}, [])

console.log(result);

Make sure both arrays are equal in size.

const description = ['One', 'Two', 'Three'];
const allPictures = ['url-1', 'url-2', 'url-3'];

const imageObject = description.map((item, index) => {
  return {
    url: item,
    description: allPictures[index]
  }
})


console.log('imageObject', imageObject)

You can use a standard for loop

const allPictures = ['url-1', 'url-2', 'url-3'];
const description = ['One', 'Two', 'Three'];

const result = [];
for (let i = 0; i < allPictures.length; i++) {
  result.push({
    url: allPictures[i],
    description: description[i]
  });
}
console.log(result)

Its simple with array's map function

  1. keep track on index, you'll use it to know the index of an element so as you can choose its corresponding element on another array as below

    const mergedArray = allPictures.map((url,index) => {

         return { url : url,
              description : description[index]
            }
      })
    
Related