1

I have a 2d array data like this:

var arr = [[a,1,b,10],[c,3,d,30],[a,2,b,20],[c,4,d,40]];

I wanted to achieve this result:

[[a,3,b,30],[c,7,d,70]]

I am thinking of sorting it and looping each element array then compare the 2 sub-elements with the ones in the previous element array but this is not efficient.

What the fastest way to do it? My actual data is thousands of lines. Thank you.

2
  • 1
    Do a and b always go together? Is this a valid array: [a,1,c,2]? Commented Aug 1, 2017 at 13:05
  • @DevonParsons, yes and no Commented Aug 1, 2017 at 13:10

1 Answer 1

1

You could use a hash table for the wanted similar values and update the array.

var array = [['a', 1, 'b', 10], ['c', 3, 'd', 30], ['a', 2, 'b', 20], ['c', 4, 'd', 40]],
    hash = Object.create(null),
    result = array.reduce(function (r, a) {
        var key = [0, 2].map(function (i) { return a[i]; }).join('|');
        if (!hash[key]) {
            hash[key] = a.slice();
            r.push(hash[key]);
            return r;
        }
        [1, 3].forEach(function (i) { hash[key][i] += a[i]; });
        return r;
    }, []);
   
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

A fast version

var array = [['a', 1, 'b', 10], ['c', 3, 'd', 30], ['a', 2, 'b', 20], ['c', 4, 'd', 40]],
    hash = Object.create(null),
    length = array.length,
    result = [],
    element, i, key, ref;

for (i = 0; i < length; i++) {
    element = array[i];
    key = array[i][0] + '|' + array[i][2];
    ref = hash[key];
    if (ref) {
        ref[1] += element[1];
        ref[3] += element[3];
        continue;
    }
    hash[key] = element.slice();
    result.push(hash[key]);
}
   
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Sign up to request clarification or add additional context in comments.

1 Comment

key = array[i][0] + '|' + array[i][0]; should be key = array[i][0] + '|' + array[i][2];, right?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.