1

I have 2 Arrays,

arr1 = [
    ['itemid-1', 'itemclass', 'timestamp'],
    ['itemid-2', 'itemclass', 'timestamp'],
    ['itemid-3', 'itemclass', 'timestamp'],
    ['itemid-5', 'itemclass', 'timestamp']
];

arr2 = [
    ['itemid-1', 'data-state', 'data-col'],
    ['itemid-3', 'data-state', 'data-col'],
    ['itemid-4', 'data-state', 'data-col']
];

The end result should be:

arr1 = [
    ['itemid-1', 'itemclass', 'timestamp', 'data-state', 'data-col'],
    ['itemid-2', 'itemclass', 'timestamp'],
    ['itemid-3', 'itemclass', 'timestamp', 'data-state', 'data-col'],
    ['itemid-5', 'itemclass', 'timestamp']
];

I want to merge values from arr2 to arr1 where itemid-x are same.

I can do this by using loops,

for(i = 0; i < arr1.length; i++){
    for(j = 0; j < arr2.length; j++){
        if(arr1[i][0] == arr2[j][0]){
            arr1[i] = arr1[i].concat(arr2[j].slice(1));
        }
    }

}

however I have recently started with underscorejs and nodejs, so I would like to know if it can be done with any existing functionality.

PS: I have found this answer interesting, but it requires the length of the arrays to be same, also it won't work if the itemid-x indices are not same in both arrays.

4

2 回答 2

1

Your code works alright, but you can improve upon this. Since you are using sorted arrays, you don't need two loops, which use m*n iterations. You can do it m+n iterations to merge two arrays where m = arr1.length and n = arr2.length

var i = j = 0;
var answer = [];

while (i < arr1.length && j < arr2.length)
{
    arr1ptr = arr1[i][0];  // Just for checking index
    arr2ptr = arr2[j][0];  // You can extract 'id' if you want

    if (arr1ptr == arr2ptr)
    {
        answer.push(arr1[i].concat(arr2[j].slice(1)));
        i++;
        j++;
    }
    else if (arr1ptr < arr2ptr)
    {
        answer.push(arr1[i]);
        i++;
    }
    else if (arr1ptr > arr2ptr)
    {
        answer.push(arr2[j]);
        j++;
    }
}

It has more lines than yours, but it is faster. Depending on size of arrays you use and ease of coding, you may want to use it.

于 2013-06-28T07:13:12.280 回答
1

I don't know if it really makes things look better or simpler to understand, but you can do

arr1.forEach(function(v, i){arr2.filter(function(v2){return v[0]==v2[0]}).forEach(function(v3){v3.slice(1).forEach(function(e){v.push(e)})})});

That for sure looks much more like js. ;)

I think there are so many different data structures and use cases that you can't really derive a common case from your data structure. element [0] is somehow special, but that is reflected in your code, not in the data structure.

To to something like considered in the answer you found interesting, can you restructure your data? arr2 = { itemid-1: [ ... ], itemid-2: [ ... ] }. Then you could do a forEach-loop, a simple lookup and a concat: arr1[i].concat(arr2[v])?

于 2013-06-28T19:40:18.907 回答