0

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!!

2
  • Are test1 length and test2 length always equal? Commented Dec 11, 2015 at 2:19
  • Yes. The same length. Commented Dec 11, 2015 at 2:20

5 Answers 5

1

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

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

Sign up to request clarification or add additional context in comments.

3 Comments

But I don't understand why you would suggest using reduce for what is exactly a mapping operation.
Because it can be used for that. In this case, map probably suits better but that may not always be the case. ;-)
@torazaburo—because it can be used for that. In this case, map probably suits better but that may not always be the case. ;-)
1

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

1 Comment

These are the only missing array operations currently in javascript. They're not even proposed for the ES7 spec. If anyone know how to get proposals into ES standards give me a shout. Or propose these yourself.
0

Try this:

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

console.log(test)

Comments

0

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!

Comments

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

5 Comments

The expression Array.apply(null, {length: test1.length}) can be replaced with the much simpler Array(test1.length). However, it's not considered a good idea to use the Array constructor that way as it can lead to difficult to find bugs.
Uh... why not just test1.map()? You do know that map doesn't modify the existing array don't you?
why not just test1.map() -> So he can use it for different lengths also (more generic answer). He said he has "21 arrays with hundreds of length". Assuming every array has the same length or the desired length can lead to unexpected behavior
So he can use it for different lengths also. I don't understand this. What you have written is exactly equivalent to test.map`.
no. how is it exactly test.map or test1.map. you can use a specific length like 5. when answering questions you think the person only needs the working code. in reality he needs to "understand" (also other people with similar problems viewing this code). So it is better to use generic stuff in the answer for people to understand and find different ways to achieve similar results.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.