0

I have the next situation:

1). one array with months from 1 to 12 and values at 0:

var months = [[1,0], [2,0], [3,0], [4,0], [5,0], [6,0], [7,0], [8,0],
              [9,0], [10,0], [11,0], [12,0], [13,0]];

2). another small array which represents the times a user has connected to the site:

 data1 = [[1, 40], [2, 50]]

what I want to do is to overlapp both arrays, running over values in array months that are in array data1.

So result has to be:

data1 = [[1,40], [2,50], [3,0], [4,0], [5,0], [6,0], [7,0], [8,0], 
         [9,0], [10,0], [11,0], [12,0], [13,0]];

can't find the way to access to the first element of each array (in months), this is what I've tried so far:

 for (var x = months.length - 1; x >= 0; x--) {
    for (var j = monthConn.length - 1; j >= 0; j--) {
        console.log(monthConn[j]); 
        for (var p = 0; p < monthConn[j].length; p++) {
           console.log(monthConn[j][p]);
        };
        // console.log(months[x].indexOf(monthConn[j]));
     };
    };

for what I'm getting in console.log:

["5", "2"]
5
2

how can I do this?

vinayakj
  • 5,591
  • 3
  • 28
  • 48
Limon
  • 1,772
  • 7
  • 32
  • 61
  • 2
    you could make months an object with month as key and value as value – depperm Jul 20 '15 at 14:58
  • @depperm I need to leave it like it is because I'm modifying a plugin that makes statistical graphs :s and it uses arrays – Limon Jul 20 '15 at 15:06
  • Not much related maybe: just wondering there are 13 elements, you said 12 – vinayakj Jul 20 '15 at 15:08
  • @vinayakj 12 elemets because each of them represents a month, and 13 is to leave a blanck space in the chart, so it will always be 0 – Limon Jul 20 '15 at 15:09
  • ok.. got it.. this was important..so while comparing no need to compare for last element. – vinayakj Jul 20 '15 at 15:12

2 Answers2

1

You just need to iterate over data1, and access the n-1-th position of months, where nis the first element of every entry:

var months = [[1,0], [2,0], [3,0], [4,0], [5,0], [6,0], [7,0], [8,0], [9,0], [10,0], [11,0], [12,0], [13,0]]

var data1 = [[1, 40], [2, 50]]

// clone months array
var overlapped = months.slice()

// for every data1 value, update corresponding month
data1.forEach(function(monthData){
  overlapped[monthData[0]-1][1] = monthData[1]
})

// et voilá
console.log(overlapped)

See fiddle.

moonwave99
  • 21,957
  • 3
  • 43
  • 64
0
var months = [[1,0], [2,0], [3,0], [4,0], [5,0], [6,0], [7,0],
              [8,0], [9,0], [10,0], [11,0], [12,0], [13,0]];
var monthConn = [[1,40],[2,50]];
var data = [];
for (var x = 0, l = months.length; x < l; x++) {
     data[x] = [0,0];
    for (var j = monthConn.length - 1; j >= 0; j--) {
           data[x][0] = months[x][0];
           data[x][1] = months[x][1];
           if(monthConn[j][0] == data[x][0]){
                  data[x][1]=monthConn[j][1];
                  break;
           }
    }
}
console.dir(months)
console.dir(data)
vinayakj
  • 5,591
  • 3
  • 28
  • 48