0

Var oldData = [ [ 2018-04-01, 10] , [ 2018-04-02, 20] , [2018-04-03, 30] ];

Var NewData = [ [ 2018-03-30, 5], [2018-03-31, 6], [2018-04-01, 22] ];

Output = [ 2018-03-30, null, 5], [2018-03-31,null, 6], [2018-04-01, 10, 22] , [2018-04-02, 20, null] , [2018-04-03, 30 null ] ]

COuld you please guide , how to achieve it.

2
Contributors
2
Replies
28
Views
4 Months
Discussion Span
Last Post by alan.davies
0
var oldData = [ [ 2018-04-01, 10] , [ 2018-04-02, 20] , [2018-04-03, 30] ];
var NewData = [ [ 2018-03-30, 5], [2018-03-31, 6], [2018-04-01, 22] ];

This data is wrong - you must have quotes around your dates:

var oldData = [ [ "2018-04-01", 10] , ["2018-04-02", 20] , ["2018-04-03", 30] ];

Otherwise js will perform the subtrations and you get:

 [ [ 2013, 10] , [ 2012, 20] , [2011, 30] ];
0

Here's what I'd do - but I'm sure you could achieve the same with fancy .map() methods:

//your original data - but note the "quoted" dates
var oldData = [ [ "2018-04-01", 10] , [ "2018-04-02", 20] , ["2018-04-03", 30] ];
var NewData = [ [ "2018-03-30", 5], ["2018-03-31", 6], ["2018-04-01", 22] ];

//a modified version of various "extend" functions
function objectify(arr, arr2)
{
     var obj = {};
    arr.forEach(function(el) { 
        obj[el[0]] = [el[1],null]; 
    });
    arr2.forEach(function(el) { 
        if(obj.hasOwnProperty(el[0])){
        obj[el[0]] = [obj[el[0]][0],el[1]];
      }else{
        obj[el[0]] = [null, el[1]];
      }
    });
    return obj;
}

//this function sorts the dates oldest to most recent
function sortObject(o) {
    return Object.keys(o).sort().reduce((r, k) => (r[k] = o[k], r), {});
}

var newObject = sortObject(objectify(oldData, NewData));

//display the contents of the new object in the console
console.log(JSON.stringify(newObject));

here's the fiddle: https://jsfiddle.net/diafol666/e5b34ndn/

Notice that it creates an object rather than an array of arrays. I believe this is better as dates (keys) are sortable and you can grab data for a specific date without scanning each individual array item or even check if that date exists (without scanning).

Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.