Search code examples
javascriptarraysmultidimensional-arrayarray-map

find punctual element in array with two elements javascript


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?


Solution

  • 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.