0

I want to merge two arrays in Javascript like this:

['First', 'Third', 'Fifth', 'Seventh', 'Ninth']
['Second', 'Fourth', 'Sixth', 'Eigth']
=> ['First', 'Second', 'Third', 'Fourth',...]

Also One array can have more elements than another one. So for example:

['E1', 'E2', 'E3']
['E4']
=> ['E1', 'E4', 'E2', 'E3']

What is the easiest way to do this?

I don't really have in idea how to do this.

note: I have underscorejs available.

4

2 回答 2

5

带下划线:

var a1 = ['First', 'Third', 'Fifth', 'Seventh', 'Ninth'];
var a2 = ['Second', 'Fourth', 'Sixth', 'Eigth'];

var result = _.compact(_.flatten(_.zip(a1, a2)));
于 2013-04-18T06:11:20.717 回答
3
a = ['First', 'Third', 'Fifth', 'Seventh', 'Ninth'];
b = ['Second', 'Fourth', 'Sixth', 'Eigth'];
c = [];
for (var i = 0; i < Math.max(a.length, b.length); i++) {
  if (i < a.length) c.push(a[i]);
  if (i < b.length) c.push(b[i]);
}
于 2013-04-18T06:10:14.783 回答