简体   繁体   中英

jQuery merge multiple javascript array values

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.

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);

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++)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM