0

I've checked the forum to see if i'll have an answer to this question but so far, i haven't. I have this 2 dimensional array that i want to sum up their values if they are the same. Here is an example.

 CAR      CAH     394
 CAR      CAH     96
 CAR      CAP     268
 DOR      CAF     71
 DOR      CAP     96
 DOR      CAP     268
 VAC      GILAB   71

After sorting the array, i have the above values. How can i add up all the duplicates in the arraylist. In this case, it will affect CAR|CAH and DOR|CAP. So instead of returning the duplicates, its goint to return one with the combined sum.

3
  • 1
    This kind of question doesn't really fit within the purpose of this site. We're here more to help solve specific problems. Usually you have to have written some code first, but it's either causing an error or behaving incorrectly. Please start by attempting a solution yourself, then ask questions about where you are getting hung up. Commented Mar 16, 2015 at 14:04
  • i want to sum up their values if they are the same if what are the same? Your question isn't exactly clear. You have two strings and a number. Are you summing them if the two strings are the same as another row? Put your source and you expected output in the question along with what you've tried. Commented Mar 16, 2015 at 14:07
  • Expected value is this: CAR CAH 490 CAR CAP 268 DOR CAF 71 DOR CAP 364 VAC GILAB 71 Commented Mar 16, 2015 at 14:22

1 Answer 1

2

If I'm understanding what you are asking correctly (because it really isn't very clear), and given that your array is already sorted, then I you can achieve what you want by using Array.reduce:

var source = [
    ["CAR", "CAH", 394],
    ["CAR", "CAH", 96],
    ["CAR", "CAP", 268],
    ["DOR", "CAF", 71],
    ["DOR", "CAP", 96],
    ["DOR", "CAP", 268],
    ["VAC", "GILAB", 71]
];

var last;
var folded = source.reduce(function(prev,curr){
    if (last) {
        if (last[0] === curr[0] && last[1] === curr[1]) {
            last[2] += curr[2];
            return prev;
        }
    }
    last = curr;
    prev.push(curr);
    return prev;
},[]);

alert(JSON.stringify(folded));

You are basically building up a new array by comparing the current value to the last value. If the first two elements match, then you add the last one to the previous value and return the array. If they don't match, then you push the new value onto the array.

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

1 Comment

yea, that worked for me, i made only one correction which is the '==='. I guess its due to the nature of values in the array. Thanks.

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.