3

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

0

4 Answers 4

3

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

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

4 Comments

Okey but how to remove item-object if is value "" or null ?
I want to push only object with values
@wamovec So, does your array contain falsy values? Update your question.
@wamovec Updated my answer... maybe that's what you're asking for.
0
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)

Comments

0

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)

Comments

0

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]
            }
      })
    

Comments

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.