Skip to content
Advertisement

Values from three arrays – Add or subtract

I have three arrays:

Each array has a “key” and a “value” for every element, for example

array: 
           0: {key: "000001", value: 10}
           1: {key: "000002", value: 20}
           // other values

array1: 
           0: {key: "000001", value: 5}
           1: {key: "000003", value: 15}
           // other values

array3: 
           0: {key: "000001", value: 10}
           1: {key: "000003", value: 3}
           // other values

And this structure is the same for the three different arrays.

Now I need to check if in these three array there are keys equal and sum or subtract the field “value”

For example:

array, array1 and array2 have the key= “000001” in all the three arrays so I sum the three value = 25.

In this way I will write only the “key” field and the sum of the “value”

I hope I was clear

I have tried in this way, but it doesn’t work as I would like:

 let outputTot = [];
  output.filter((newDataOutput) => {
    return output1.filter((newDataOutput1) => {
      return output2.filter((newDataOutput2) => {
        if(newDataOutput.key == newDataOutput1.key && newDataOutput.key == newDataOutput2.key){
          outputTot.push({
            'key': newDataOutput.key,
            'value': newDataOutput.value + newDataOutput1.value + newDataOutput2.value
          })
        }
        else if(newDataOutput.key == newDataOutput1.key){
          outputTot.push({
            'key': newDataOutput.key,
            'value': newDataOutput.value + newDataOutput1.value
          })
        }
        else if(newDataOutput.key == newDataOutput2.key){
          outputTot.push({
            'key': newDataOutput.key,
            'value': newDataOutput.value + newDataOutput2.value
          })
        }
        else if(newDataOutput1.key == newDataOutput2.key){
          outputTot.push({
            'key': newDataOutput1.key,
            'value': newDataOutput1.value + newDataOutput2.value
          })
        }
      })
    })
  })

I had thought of calculating all 4 cases but obviously it doesn’t work like that.

How could I do?

EDIT:

What I expect:

my outputTot like:

> [0] key: "000001", value: 25
> [1] key: "000002", value: 20
> [2] kye: "000003", value: 18

Advertisement

Answer

I assume, you need reduce function to achieve the expected output. You can first group by the data using key and then take Object.values to get array out of it.

const arr = [{key: "000001", value: 10},{key: "000002", value: 20}];
const arr1 = [{key: "000001", value: 5},{key: "000002", value: 20}];
const arr2 = [{key: "000001", value: 10},{key: "000003", value: 3}];

const result = Object.values([...arr,...arr1,...arr2].reduce((a,{key, value}, i)=>{
    a[key] ??= {key, value:0};
    i==2 ? a[key].value-=value : a[key].value+=value;
    return a;
},{}));

console.log(result);
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement