Search code examples
javascriptarrayssum

Addition of values inside an Array according to certain value


I have an array like this:

let array = [[0, 1, 4.75], [0, 1, 2.12], [0, 3, 8.1]];

Expected output:

let expectedOutput = [[0, 1, 6.87], [0, 3, 8.1]];

In this case 4.75 + 2.12 has been summed up because first two values were matching [0, 1].

I want to lookup the first and second value in the sub-array und sum the third value of all the sub-arrays that has the same first and second value. Can you please help me out?


Solution

  • When building the result, check if the current element matches a previous one, and then either add only the value or the whole element:

    let array = [[0, 1, 4.75], [0, 1, 2.12], [0, 3, 8.1]];
    
    const result = array.reduce( (r, [x,y,v], i) => (i = r.find(e => e[0] === x && e[1] === y), i ? i[2] += v : r.push([x,y,v]), r), [])
    
    console.log(result)