0

I have two arrays. Length of array A is fixed and length of array B depends on DB result. Both Array A and B are key(timestamp) value(count) pair arrays. In array B some timestamp are missing, I need to populate missing timestamp value as zero. If timestamp is present I need to use the value. How do I achieve this?

Ex: Array A = {[time:1481280113, value: 0], [time:1481280053, value: 0],..}

Array B = {[time:1481280113, value: 1234], [time:1481279983, value: 123],..}

Result A = {[time:1481280113, value: 0], [time:1481280053, value: 0],[time:1481279983, value: 123]..}

Ameya
  • 69
  • 2
  • 10
  • So in Result A `time:1481280113, value: 0` the value should actually be `1234` if I got it right !? – caramba Dec 09 '16 at 10:48
  • you say A/B is array but in syntax you have described it as object {} your model defines as object of arrays whereas ideal model would be array of objects – Vinod Louis Dec 09 '16 at 10:48
  • Possible duplicate of [How to merge two arrays in Javascript and de-duplicate items](http://stackoverflow.com/questions/1584370/how-to-merge-two-arrays-in-javascript-and-de-duplicate-items) – caramba Dec 09 '16 at 10:51
  • With this notation, you have not 2 arrays, but 2 (invalid) JSON objects... – Tistkle Dec 09 '16 at 10:56
  • @caramba: Yes you are right. – Ameya Dec 09 '16 at 11:10
  • @Tistkle Ok you are right, is there anyway I can get the result as I want it? I had to create array A as I receive the jSon response. – Ameya Dec 09 '16 at 11:11
  • Post your Json response so – kevin ternet Dec 09 '16 at 13:43
  • Thank you all, I saved myself time and wrote a better query on DB side to fetch data. No need to merge any array. Thank you. – Ameya Dec 13 '16 at 09:31

1 Answers1

0

Do you know the MergeSort algorithm? You can use the mege part of it, so:

function mergeArrays(arr1, arr2){
    var a1 = sort array1; //any way you want (EX. 1 < 2 < 3 ...)
    var a2 = sort array2; //any way you want (EX. 1 < 2 < 3 ...)
    var result = [];

    while(a1.length > 0 && a2.length > 0) {
        if(a1[0] < a2[0]) { result.push(a1.shift()); }
        if(a1[0] > a2[0]) { result.push(as.shift()); }
        if(a1[0] == a2[0]) { /* equals, do whatever you want to resolve this */ }       
    }   
    if (a1.length == 0) { result.concat(a2); /* no more elements in a1, append to result the remains of a2*/ }
    if (a2.length == 0) { result.concat(a1); /* no more elements in a2, append to result the remains of a1*/ }

    return result
}

This returns the merged array (and sorted), but, if you don't drop duplicates in a1[0] == a2[0] case, you will obtain that duplicates, so, be careful there.

Tistkle
  • 500
  • 6
  • 13