简体   繁体   中英

How to combine arrays using javascript

How can I combine test1 and test2 to get the same result as test? I found concat() and join() can do the combination but can't get the result I want.

  var test1 = [1,5,7,4]
    var test2 = ["apple","banana","apple","banana"]
    var test = [
       {xValue:1,yValue:"apple"},
       {xValue:5,yValue:"banana"},
       {xValue:7,yValue:"apple"},
       {xValue:4,yValue:"banana"}
    ]
console.log(test);
console.log(test1);
console.log(test2);

I have 21 arrays with hundreds of length for each one in my real case. I am trying to combine them together and get the result like the example above. Thanks!!

In the case where you want to create a new array from existing, map and reduce are candidates, eg

 var test1 = [1,5,7,4] var test2 = ["apple","banana","apple","banana"] var test = test1.map(function(v, i){ return {xValue:v, yValue: test2[i]}; }); document.write(JSON.stringify(test)) var test2 = test1.reduce(function(acc, v, i) { acc.push({xValue:v, yValue: test2[i]}); return acc; }, []) document.write('<br><br>' + JSON.stringify(test2)) 

It is for this reason I wrote the libraries array.and and array.stride . Both are very small pieces of code that can run on both the browser and node.js that add the features of merging arrays and iterating an array by more than one item at a time. These functionality are available in other languages as zip/unzip (or in the case of tcl, foreach , which can do both zipping and unzipping).

[].and() merges two arrays into a single array:

[1,2].and(['a','b']); // returns [1,'a',2,'b']

[].stride() is like foreach but can iterate multiple items each loop:

[1,2,3,4].stride(function(a,b){
    console.log(a,b); // logs 1,2 then 3,4
});

Using them together you can write very readable and obvious code to get what you want:

var test = test1.and(test2).stride(function(x,y){
    return {xValue:x, yValue:y};
});

Try this:

var test = [];
for (i = 0; i < test1.length; i++) { 
    test.push({xvalue:test1[i], yvalue:test2[i]});
}

console.log(test)

Here is what I would do if I were you:

  var test1 = [1,5,7,4]; var test2 = ["apple","banana","apple","banana"]; var test = test1.map(function(v,i){ return {"xValue":v,"yValue":test2[i]}; }); document.write(JSON.stringify(test)); document.write(test); document.write(test1); document.write(test2); 

Try it!

var zippedArray = Array.apply(null, {length: test1.length}).map(function (e, i) {
    var obj = {
      xVal: test1[i],
      yVal: test2[i]
    };
    return obj;
});

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