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.

Recommended Answers

All 2 Replies

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] ];

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

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.