0

I have an array which holds an arrays of data and values. I am running in to a problem of figuring out the unique array based on those data I have.

ex:
var x =[[1,2,3,abc],[3,4,5,xyz],[5,6,7,abc]];
I wanted:

var y =[[6,8,10,abc],[3,4,5,xyz]];

so I had this feeling to loop through the first array to check the possible match of the text and add the corresponding value and return the integrated array.

need some help to understand these logic.

appreciated any help.

DC1
  • 74
  • 6
  • I think you want to [compare arrays to arrays](http://stackoverflow.com/a/14853974/2033671) –  Dec 20 '13 at 21:02
  • Do you mean [merging arrays](http://stackoverflow.com/questions/1584370/how-to-merge-two-arrays-in-javascript)? – Drake Sobania Dec 20 '13 at 21:04
  • 1
    I don't know how to get started, I want to compare the string part on each array with another array, if match found I want to combine the number value of those matched items and keep the string part as one array. ex: var x =[[1,2,3,abc],[3,4,5,xyz],[5,6,7,abc],[7,8,9,abc]]; I wanted: to compare in between x arrays and return var y =[[13,16,19,abc],[3,4,5,xyz]]; – DC1 Dec 20 '13 at 21:10
  • What is the data's origin? – Drake Sobania Dec 20 '13 at 21:23
  • these are the json data and I have captured it in an array of Arrays – DC1 Dec 20 '13 at 21:34

1 Answers1

1

See this example on jsFiddle.

GroupBy reference

function GroupBy(a, keySelector, elementSelector)
{
    elementSelector = elementSelector || function(e) { return e; };

    var key;
    var hashs = {};
    for (var i = 0, n = a.length; i < n; ++i)
    {
        key = keySelector(a[i]);
        hashs[key] = hashs[key] || []
        hashs[key].push(a[i]);
    }

    return hashs;
}

With this method I can group arrays by a centain key:

var x =[[1,2,3,"abc"],[3,4,5,"xyz"],[5,6,7,"abc"]];

var grouped = GroupBy(x, function(k) { return k[k.length-1]; });

I am grouping by the last element of each array inside the big array. Then I accumulate the values and remove the ones I already computed:

for (var i in grouped)
{
    var arr = grouped[i];
    for (var j = 1; j < arr.length; )
    {
        for (var p = 0; p < arr[j].length - 1; ++p)
        {
            arr[0][p] += arr[j][p];
        }
        arr.splice(j, 1);
    }
}

The result is

console.log(grouped);

result

Community
  • 1
  • 1
BrunoLM
  • 97,872
  • 84
  • 296
  • 452