1

I have defined two JavaScript variables that are arrays into an array like:

var myMondaysImpressionsData = new Array(['2013-01-21', 2015], ['2013-01-28', 2967], ['2013-02-04', 2419], ['2013-02-11', 1311], ['2013-02-18', 1398], ['2013-02-25', 86161], ['2013-03-04', 216865], ['2013-03-11', 105252], ['2013-03-18', 141978], ['2013-03-25', 4647], ['2013-04-01', 46339], ['2013-04-08', 19920]);

and:

var myMondaysImpressionsPaidData = new Array([0], [0], [0], [0], [0], [69428], [186482], [74850], [107281], [0], [32781], [0]);

It's kinda mandatory to use this form because is for further scopes. My issue is that I want to take the values found in the second array and add them like that for example:

var example = new Array(['2013-01-21', 2015, 0], ['2013-01-28', 2967, 0], ['2013-02-04', 2419, 0], ['2013-02-11', 1311, 0], ['2013-02-18', 1398, 0], ['2013-02-25', 86161, 69428], ['2013-03-04', 216865, 186482], ['2013-03-11', 105252, 74850], ['2013-03-18', 141978, 107281], ['2013-03-25', 4647, 0], ['2013-04-01', 46339, 32781], ['2013-04-08', 19920, 0]);

in the first array. Like I said, I have to reach the form shown above in the example variable. How is this possible in JavaScript? What method should be used in this case of scenarios?

3 Answers 3

3

Use a simple loop:

for (var i = 0; i < myMondaysImpressionsData.length; i++) {
    if (i < myMondaysImpressionsPaidData.length) {
        myMondaysImpressionsData[i].push(myMondaysImpressionsPaidData[0]);
    }
}

If you want to get a new array, that is not change the first one, simply copy it before. In JavaScript, this is done using

var copy = array.slice();
Sign up to request clarification or add additional context in comments.

2 Comments

Does the OP want a new array, or the myMondaysImpressionsData array modified?
I would like to modify the array, not to create a new one if is possible :)
0

One possible solution for modern browsers:

var example = myMondaysImpressionsData.slice().map(function(e, i) {
    return e.concat(myMondaysImpressionsPaidData[i]);
});

If you need old browsers support use shim for map() method from MDN.

Comments

0

Using the concat function of Array and assuming you would like to create a new object containing the final result I would solve it like this.

var example = [], length = myMondaysImpressionsPaidData.length, i;
for (i = 0; i < length; i++) {
    example.push(myMondaysImpressionsData[i].concat(myMondaysImpressionsPaidData[i]));
}

Comments

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.