let's say we have two JavaScript arrays like this:
var firstNameArray = ["Jack", "Indiana", "James"];
var lastNameArray = ["Sparrow", "Jones", "Bond"];
I want the output to be:
var result = ["Jack Sparrow","Indiana Jones","James Bond"];
Note: firstNameArray & lastNameArray can have dynamic values*
How do I merge elements of two arrays in JavaScript to get this result?
CodePudding user response:
Using traditional for
loop
var firstNameArray = ["Jack", "Indiana", "James"];
var lastNameArray = ["Sparrow", "Jones", "Bond"];
let merged = [];
for (let i = 0; i < firstNameArray.length; i ) {
merged.push(`${firstNameArray[i]} ${lastNameArray[i]}`)
}
console.log(merged);
Using reduce
method
var firstNameArray = ["Jack", "Indiana", "James"];
var lastNameArray = ["Sparrow", "Jones", "Bond"];
const merged = firstNameArray.reduce((arr, item, index) => {
arr.push(`${item} ${lastNameArray[index]}`);
return arr;
}, []);
console.log(merged)
Using map
var firstNameArray = ["Jack", "Indiana", "James"];
var lastNameArray = ["Sparrow", "Jones", "Bond"];
let merged = firstNameArray.map((e,index) => {
return `${e} ${lastNameArray[index]}`;
});
console.log(merged);
CodePudding user response:
var result = firstNameArray.map((it,index)=>it ' ' lastNameArray[index]);
CodePudding user response:
You can iterate any array (assuming both the arrays will contain equal number of elements) using map and build the new set with concatenation both the array elements based on index.
Demo :
const firstNameArray = ["Jack", "Indiana", "James"];
const lastNameArray = ["Sparrow", "Jones", "Bond"];
const finalArray = firstNameArray.map((item, index) => {
return `${item} ${lastNameArray[index]}`
});
console.log(finalArray);