0

I have two nodelists nl_first & nl_second.

Anyone of the two lists can be bigger than the other.

  1. I will start with nl_first and populate the array in a way that first & second element in the array will be nl_first[0] & nl_second[0].
  2. Similarly, third and forth will be nl_first[1] & nl_second[1].
  3. Now, if nl_second has finished, I will simply append the elements in nl_first in the array.

Visually, if

nl_first = a,b,c,d,e
nl_second = x,y,z

I need my array to have a,x,b,y,c,z,d,e.

How can I accomplish that elegantly?

yetanotherstacker
  • 285
  • 2
  • 4
  • 12
  • @ngsiolei Oops. I missed d. Sorry. – yetanotherstacker Mar 21 '12 at 18:30
  • No elegant way. There's a `zip` method in some languages, but it isn't available in js (exists in some frameworks, though) See also: http://stackoverflow.com/questions/4856717/javascript-equivalent-of-pythons-zip-funciton – kirilloid Mar 21 '12 at 18:56

3 Answers3

0
var one = ['a', 'b', 'c', 'd', 'e'];
var two = ['x', 'y', 'z'];
var combined = [];
for (var i = 0; i < one.length; i++) {
  combined.push(one[i]);
  if (two[i]) {
    combined.push(two[i]);
  }
}
console.log(combined);
// ["a", "x", "b", "y", "c", "z", "d", "e"]

Keep in mind that if two is longer than one the extra two elements will not end up in the array.

abraham
  • 46,583
  • 10
  • 100
  • 152
0

my dirty implementation, :p

var nl_first = "a,b,c,d,e";
var nl_second = "1,2,3";
console.log(customJoin(nl_first, nl_second));
//a,1,b,2,c,3,d,e

var nl_first = "a,b,c,d,e";
var nl_second = "1,2,3,4,5";
console.log(customJoin(nl_first, nl_second));
//a,1,b,2,c,3,d,4,e,5

var nl_first = "a,b,c,d,e";
var nl_second = "1,2,3,4,5,6";
console.log(customJoin(nl_first, nl_second));
//a,1,b,2,c,3,d,4,e,5,6

function customJoin(first, second) {
  if (first.length > second.length) {
    var secondArray = second.split(',');
    secondArray.reverse();
    var result = first.replace(/,/g, function (text) {
      var item = secondArray.pop();
      return (item) ? text + item + text: text;
    }); 
    return result;
  } else {
    var firstArray = first.split(',');
    firstArray.reverse();
    second = ',' + second;
    var result = second.replace(/,/g, function (text) {
      var item = firstArray.pop();
      return (item) ? text + item + text: text;
    }); 
    result = result.replace(/^,/, '');
    return result;
  }
}
ngsiolei
  • 614
  • 3
  • 5
0
    var a = ['a', 'b', 'c', 'd', 'e', 'f'];
    var b = ['j', 'r', 'o', 't', 'a'];

    function mergeArrays(a, b)
    {

        var c = [];
        var len = a.length;
        if (b.length > len) len = b.length;
        for (var i = 0; i < len; i++)
        {
            if (i < a.length) c.push(a[i]);
            if (i < b.length) c.push(b[i]);
        }
        alert(c);
    }

    $().ready(function ()
    {
        mergeArrays(a, b);
        mergeArrays(b, a);
    });
J. S.
  • 1