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
and lastNameArray
can have dynamic values.
How do I merge elements of two arrays in JavaScript to get this result?
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);
var 结果 = firstNameArray.map((it,index)=>it+' '+lastNameArray[index]);
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);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.