0

I already searched for my issue, however, i did not find something, that matches my needs. I want to merge (sum) multiple series of data into a single array. Any dataset that matches the key, shall be summed in the resulting array.

Please see sample data and expected result:

var power1 = [
  {
    "time": 10,
    "power": 100
  },
  {
    "time": 20,
    "type": 200
  },
  {
    "time": 30,
    "type": 300
  }
]
var power2 = [
  {
    "time": 20,
    "type": 200
  },
  {
    "time": 30,
    "type": 300
  },
  {
    "time": 40,
    "type": 400
  }
]    
var result = [
  {
    "time": 10,
    "type": 100
  },
  {
    "time": 20,
    "type": 400
  },
  {
    "time": 30,
    "type": 600
  },
  {
    "time": 40,
    "type": 400
  }
]

Since this should happen with thousands of items, it should be reasonable fast. Could a Map as intermediate help here?

Thanks in advance

3
  • After you concat 2 arrays, you have all kind of answers here Commented Aug 3, 2021 at 22:37
  • Does my answer work for you? Commented Aug 4, 2021 at 18:50
  • Unfortunately, this did not work for me. But i am using Node Red. Maybe there are limitations regarding JavaScript. However, the hint from @NikolaPavicevic helped me. The overall solution now looks different: since my data is coming from an InfluxDB, i can do all that math in a query. Thanks a lot! Commented Aug 12, 2021 at 10:40

1 Answer 1

1

You can concat the two arrays and then perform a reduce operation over it with an object to store the values for each key.

var power1=[{time:10,type:100},{time:20,type:200},{time:30,type:300}],power2=[{time:20,type:200},{time:30,type:300},{time:40,type:400}];
const res = Object.values(
  power1.concat(power2).reduce((acc, {type, time})=>{
    (acc[time] ??= {time, type: 0}).type += type;
    return acc;
  }, {})
);
console.log(res);

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

2 Comments

what is this ??=
@lonewarrior556 it's logical nullish assignment: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…

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.