3

I believe that arrays can be joined and then put into a string with a custom separator like this:

var a1 = ["apple","orange"];
var a2 = ["hot", "cold"];
var a3 = a1.concat(a2); 
var str = a3.join("_");

However, the result would be:

apple_orange_hot_cold  

I am looking to join each member of a1 with the corresponding a2 member, where correspondence happens by order in the array. Assume that number of members in a1 always equals the number in a2. So, i'd like the output to be a string that looks like this:

apple_hot_orange_cold

What is the best way to accomplish this?

JJ2357
  • 153
  • 2
  • 8

4 Answers4

2

Combine your arrays with reduce function instead of concat:

var a1 = ["apple","orange"];
var a2 = ["hot", "cold"];

var str = a1.reduce(function(r, v, i) {
    r.push(v, a2[i]);
    return r;
},[]).join('_');

solution with ES6 syntax:

let str = a1.reduce((r, v, i) => [...r, v, a2[i]], []).join('_');

or alternative solution with map:

let str = a1.map((v, i) => `${v}_${a2[i]}`).join('_');
madox2
  • 49,493
  • 17
  • 99
  • 99
1

I would iterate over all items and combine a new array with the items, if there is an item.

This solution works for equal and unequal array length.

var a1 = ["apple", "orange", 'ddd'],
    a2 = ["hot", "cold"],
    result = function (a1, a2) {
        var l = Math.max(a1.length, a2.length),
            i,
            r = [];
        for (i = 0; i < l; i++) {
            i in a1 && r.push(a1[i]);
            i in a2 && r.push(a2[i]);
        }
        return r;            
    }(a1, a2);

document.write(result.join('_'));
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
0

You can do this with a simple for loop:

var a1 = ["apple","orange"],
    a2 = ["hot", "cold"],
    str = "";

for (var i = 0; i < a1.length; i++)
  str += (i === 0 ? "" : "_") + a1[i] + "_" + a2[i]

alert(str);

The (i === 0 ? "" : "_") part simply checks to see if we're on the first iteration; if we are, this adds nothing to the front, otherwise it adds an extra underscore.

James Donnelly
  • 126,410
  • 34
  • 208
  • 218
0

Another option:

var a1 = ["apple","orange"];
var a2 = ["hot", "cold"];
var a3 = [];

a1.forEach(function(a, i) {
  [a, a2[i]].forEach(function(b) {
    a3.push(b);
  });
});

alert(a3.join('_'));

Or with ES6 syntax, you can do it as a super clean one-liner:

var a1 = ["apple","orange"];
var a2 = ["hot", "cold"];
var a3 = [];

a1.forEach((a, i) => [a, a2[i]].forEach((b) => a3.push(b)));

alert(a3.join('_'));
jeffdill2
  • 3,968
  • 2
  • 30
  • 47