0

I have came across a situation where I need to merge values from two different arrays into single one.

My First array values are like :

[35.3,35.3,35.3,35.3,35.2,33.8,29.8,21.5]

Second Array values are like :

[10,20,30,40,50,60,70,80]

Resulting array:

[[35.3,10],[35.3,20],[35.3,30],[35.4,40],[35.2,50],[33.8,60],[29.8,70],[21.5,80]]

Appreciate your help.

Thanks.

Ved
  • 8,577
  • 7
  • 36
  • 69
ashish.chotalia
  • 3,696
  • 27
  • 28

2 Answers2

2

Here's a simple function in pure javascript for equal length arrays:

var a = [35.3,35.3,35.3,35.3,35.2,33.8,29.8,21.5];
var b = [10,20,30,40,50,60,70,80];

function merge(a, b) {
    if (a.length == b.length) {
        var c = [];
        for (var i = 0; i < a.length; i++) {
            c.push([a[i], b[i]]);
        }
        return c;
    }
    return null;
}

var c = merge(a, b);
Maehler
  • 6,111
  • 1
  • 41
  • 46
  • I've got the completly same solution :-) for this little function, you don't must use jQuery... pure javascript will work also – Tobi Apr 25 '12 at 05:48
0

Since you already want to use a library, here's a suggestion using another one (jQuery is not really the tool for non-DOM-related things like that):

http://documentcloud.github.com/underscore/#zip

zip_.zip(*arrays)

Merges together the values of each of the arrays with the values at the corresponding position. Useful when you have separate data sources that are coordinated through matching array indexes. If you're working with a matrix of nested arrays, zip.apply can transpose the matrix in a similar fashion.

_.zip(['moe', 'larry', 'curly'], [30, 40, 50], [true, false, false]);
=> [["moe", 30, true], ["larry", 40, false], ["curly", 50, false]]

Since your arrays have the same size, here's a simple function that does the job,:

function zip(arr1, arr2) {
    var arr = new Array(arr1.length);
    for(var i = 0; i < arr1.length; i++) {
        arr.push([arr1[i], arr2[i]]);
    }
    return arr;
}

To make it take the shortest array and ignore additional elements in the other array:

for(var i = 0, len = Math.min(arr1.length, arr2.length); i < len; i++)
ThiefMaster
  • 310,957
  • 84
  • 592
  • 636
  • Thanks for looking into this. If I can do this with jQuery/javascript I will prefer that, else I need to add reference to this external js file. – ashish.chotalia Apr 25 '12 at 05:41
  • Well you could take the function and its dependencies and paste them into your code. They'll work with minor modifications. If both arrays always have the same size you can make the function's code even shorter. – ThiefMaster Apr 25 '12 at 05:42
  • Yeah, both will be the same size. – ashish.chotalia Apr 25 '12 at 05:43