Search code examples
google-apps-scriptmultidimensional-arrayreducesumifs

How to Sum Duplicate Items in a Two Dimensional Array using Apps Script?


How would you take an array such as this:

arr1 = [[1150-500101-1000005530, 2750.0],  
        [1150-500101-1000005530, 275.0], 
        [1150-500101-1000008371, 825.0],  
        [1150-500101-1000014950, 550.0],  
        [1150-500101-1000019105, 589.0],  
        [1150-500101-1000019111, 589.0],  
        [1150-500101-1000019111, 275.0]]

and merge duplicate values from the first value of each array (arr1[i][0])

in order to get something like this:

reducedArr1 = [[1150-500101-1000005530, 3025.0],
               [1150-500101-1000008371, 825.0],
               [1150-500101-1000014950, 550.0],
               [1150-500101-1000019105, 589.0],
               [1150-500101-1000019111, 864.0]]

These values are changing constantly as they are pulled from a Google Sheet.

I have tried to find similar problems like this but haven't found anything that applies without assigning a key. What I am really looks for is a SUMIF made for two dimensional arrays so I can add this new array to a Google Sheet report.

Thanks


Solution

  • I believe your goal is as follows.

    • You want to convert the value of arr1 to reducedArr1 using Google Apps Script.

    As another approach, how about the following sample script?

    Sample script:

    // This is your sample input value.
    const arr1 = [
      ["1150-500101-1000005530", 2750.0],
      ["1150-500101-1000005530", 275.0],
      ["1150-500101-1000008371", 825.0],
      ["1150-500101-1000014950", 550.0],
      ["1150-500101-1000019105", 589.0],
      ["1150-500101-1000019111", 589.0],
      ["1150-500101-1000019111", 275.0]
    ];
    
    const reducedArr1 = [...arr1.reduce((m, [a, b]) => m.set(a, m.has(a) ? m.get(a) + b : b), new Map())];
    console.log(reducedArr1);

    Testing:

    When the above script is run, the following result is obtained.

    [
      ["1150-500101-1000005530", 3025],
      ["1150-500101-1000008371", 825],
      ["1150-500101-1000014950", 550],
      ["1150-500101-1000019105", 589],
      ["1150-500101-1000019111", 864]
    ]
    

    References: