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