1

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"];
chriss
  • 4,349
  • 8
  • 29
  • 36
  • and what have you tried? – Nina Scholz Mar 04 '16 at 12:16
  • And you didn't try [`map()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map) – Tushar Mar 04 '16 at 12:16
  • are the arrays always of equal length? – supersan Mar 04 '16 at 12:17
  • var a = ["a", "s", "d","w"]; var b = ["q", "w", "e"]; var possibility1 = a.map(function(item, i) { return item + ' ' + b[i] }) alert(possibility1); var possibility2=a.concat(b); alert(possibility2); if there are two same thing use map if u want for one time,if y want for two time than use concat – mr. pc_coder Mar 04 '16 at 12:22

4 Answers4

2
a.map((e, i) => e + ' ' + b[i])

Tushar has got it right and probably the best and most efficient way

SemperFi
  • 2,358
  • 6
  • 31
  • 51
1

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.

Chris
  • 57,622
  • 19
  • 111
  • 137
0

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]
})

or Array.prototype.reduce:

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]), [])
dfsq
  • 191,768
  • 25
  • 236
  • 258
0

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)
htoniv
  • 1,658
  • 21
  • 40