I'm looking for a simple way (can be with jQuery) to combine two string arrays:
var a = ["a", "s", "d"];
var b = ["q", "w", "e"];
to produce:
var c = ["a q", "s w", "d e"];
I'm looking for a simple way (can be with jQuery) to combine two string arrays:
var a = ["a", "s", "d"];
var b = ["q", "w", "e"];
to produce:
var c = ["a q", "s w", "d e"];
a.map((e, i) => e + ' ' + b[i])
Tushar has got it right and probably the best and most efficient way
Try this (check the output in the console):
var a = ["a", "s", "d"]; //add or remove items
var b = ["q", "w", "e"]; //add or remove items
if(a.length>b.length) {
var biggest = a.slice();
var smallest = b.slice();
} else {
var biggest = b.slice();
var smallest = a.slice();
}
var c = biggest.map(function(num, i) {
if(i < smallest.length) return num + " " + smallest[i];
return num;
});
console.log(c);
//CHECK OUTPUT IN CONSOLE
This allows for the arrays to be different in size, and still produce same result. Otherwise just map on a
do the conditional on b
Here is a Live Demo.
You either use Array.prototype.map:
var a = ["a", "s", "d"];
var b = ["q", "w", "e"];
var c = a.map(function(item, i) {
return item + ' ' + b[i]
})
var c = a.reduce(function(prev, item, i) {
return prev.concat(item + ' ' + b[i])
}, [])
Whatever you like more. If you are in ES2015 friendly world then using arrow functions make it even nicer:
// map
var c = a.map((item, i) => item + ' ' + b[i])
// reduce
var c = a.reduce((prev, item, i) => prev.concat(item + ' ' + b[i]), [])
If the array length is equal for a and b
then you can try this.
var a = ["a", "s", "d"];
var b = ["q", "w", "e"];
var c = [];
for (var i=0;i<a.length; i++) {
val = a[i] + " " + b[i];
c.push(val)
}
console.log(c)