I have two arrays I would like to merge in to one. How can I do this ?
Array A ["Chicken", "cow", "lamb"]
Array B ["egg", "beef", "chop"]
Desired outcome:
Array C ["Chicken egg", "cow beef", "lamb chop"]
.map()
is useful for writing this cleanly.
http://jsbin.com/heromuruka/1/edit?js,console
var a = ["Chicken", "cow", "lamb"],
b = ["egg", "beef", "chop"];
var c = a.map(function (e, i) {
return e + ' ' + b[i];
});
The value of e
is the current element, and the value of i
is the current index.
Assuming that your arrays are defined like this:
var arrayA = ["Chicken", "cow", "lamb"];
var arrayB = ["egg", "beef", "chop"];
var arrayC = [];
You can use this:
for (var i = 0; i < arrayA.length; i++) {
arrayC[i] = arrayA[i] + ' ' + arrayB[i];
}
See a working example below:
var arrayA = ["Chicken", "cow", "lamb"]; var arrayB = ["egg", "beef", "chop"]; var arrayC = []; for (var i = 0; i < arrayA.length; i++) { arrayC[i] = arrayA[i] + ' ' + arrayB[i]; } console.log(arrayC);
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.