开发者

How to merging javascript arrays and order by position?

开发者 https://www.devze.com 2023-03-08 20:13 出处:网络
Is there anyway to merge ar开发者_StackOverflowrays in javascript by ordering by index/position. I\'m try to accomplish this and haven\'t been able to find any examples of this.

Is there anyway to merge ar开发者_StackOverflowrays in javascript by ordering by index/position. I'm try to accomplish this and haven't been able to find any examples of this.

var array1 = [1,2,3,4] var array2 = [a,b,c,d] var array3 = [!,@,#,$]

var merged array = [1,a,!,2,b,@,3,c,#,4,d,$]

I know you can use concat() to put one after the other.


As long as the arrays are all the same length you could just do:

var mergedArray = [];
for (var i = 0, il = array1.length; i < il; i++) {
  mergedArray.push(array1[i]);
  mergedArray.push(array2[i]);
  mergedArray.push(array3[i]);
}

EDIT: For arrays of varying lengths you could do:

var mergedArray = [];
for (var i = 0, il = Math.max(array1.length, array2.length, array3.length); 
     i < il; i++) {
  if (array1[i]) { mergedArray.push(array1[i]); }
  if (array2[i]) { mergedArray.push(array2[i]); }
  if (array3[i]) { mergedArray.push(array3[i]); }
}


This should work for arrays of ANY length:

var mergeArrays = function () {
    var arr = [],
        args = arr.slice.call(arguments),
        length = 0;

    for (var i = 0, len = args.length; i < len; i++) {
        length = args[i].length > length ? args[i].length : length;
    }

    for (i = 0; i < length; i++) {
        for (var j = 0; j < len; j++) {
            var value = args[j][i];

            if (value) {
                arr.push(value);
            }
        }
    }

    return arr;
};

Example:

var array1 = [1,2,3,4];
var array2 = ['a','b','c','d','e','f','g','h','i','j','k','l'];
var array3 = ['!','@','#','$','%','^','&','*','('];

mergeArrays(array1, array2, array3);
// outputs: [1, "a", "!", 2, "b", "@", 3, "c", "#", 4, "d", "$", "e", "%", "f", "^", "g", "&", "h", "*", "i", "(", "j", "k", "l"]

This would work also (a little more terse syntax):

var mergeArrays = function () {
    var arr = [],
        args = arr.slice.call(arguments),
        length = Math.max.apply(null, args.map(function (a) { return a.length; }));

    for (i = 0; i < length; i++) {
        for (var j = 0, len = args.length; j < len; j++) {
            var value = args[j][i];

            if (value) {
                arr.push(value);
            }
        }
    }

    return arr;
};


For arrays that are all the same size, where you pass one or more arrays as parameters to merge:

function merge()
{
    var result = [];
    for (var i=0; i<arguments[0].length; i++)
    {
        for (var j=0; j<arguments.length; j++)
        {
            result.push(arguments[j][i]);
        }
    }
    return result;
}

var array1 = ['1','2','3','4'];
var array2 = ['a','b','c','d'];
var array3 = ['!','@','#','$'];
var merged = merge(array1, array2, array3);


Nothing built in, but it wouldn't be hard to manage:

var maxLength = Math.max(array1.length, array2.length, array3.length),
    output = [];

for (var i = 0; i < maxLength; i++) {
    if (array1[i] != undefined) output.push(array1[i]);
    if (array2[i] != undefined) output.push(array2[i]);
    if (array3[i] != undefined) output.push(array3[i]);
}


try this...

var masterList = new Array();
var array1 = [1,2,3,4];
var array2 = [a,b,c,d];
var array3 = [!,@,#,$];
for(i = 0; i < array1.length; i++) {
    masterList.push(array1[i]);
    masterList.push(array2[i]);
    masterList.push(array3[i]);
}


It looks like you want to "zip" some number of same-length arrays into a single array:

var zip = function() {
  var numArrays=arguments.length
    , len=arguments[0].length
    , arr=[], i, j;
  for (i=0; i<len; i++) {
    for (j=0; j<numArrays; j++) {
      arr.push(arguments[j][i]);
    }
  }
  return arr;
};

zip([1,2], ['a', 'b']); // => [1, 'a', 2, 'b']
zip([1,2,3], ['a','b','c'], ['!','@','#']); // => [1,'a','@',...,3,'c','#']

If the input arrays could be of different length then you've got to figure out how to deal with that case...


Yes, there is some way to do that. Just:

  • loop through the larger array,
  • until at the currently processed position both arrays have elements, assign them one-by-one to the new array,
  • after the shorter array ends, assign only elements from the longer array,

The resulting array will have the elements ordered by the index from the original arrays. From your decision depends, position in which one of these arrays will have higher priority.


This works for any number of array and with arrays of any length.

function myMerge() {
  var result = [],
      maxLength = 0;
  for (var i = 0; i < arguments.length; i++) {
    if (arguments[i].length > maxLength) { maxLength = arguments[i].length; }
  }
  for (var i = 0; i < maxLength; i++) {
    for (var j = 0; j < arguments.length; j++) {
      if (arguments[j].length > i) {
        result.push(arguments[j][i]);
      }
    }
  }
  return result;
}


Eli beat me to the punch up there.

var posConcat = function() {
    var arrays = Array.prototype.slice.call(arguments, 0),
        newArray = [];

    while(arrays.some(notEmpty)) {
        for(var i = 0; i < arrays.length; i++) {
            if(arguments[i].length > 0)
                newArray.push(arguments[i].shift());
        }
    }

    return newArray;
},

notEmpty = function() { return arguments[0].length > 0; };

Usage:

var orderedArray = posConcat(array1,array2,array3);

Sample: http://jsfiddle.net/HH9SR/

0

精彩评论

暂无评论...
验证码 换一张
取 消