1

This seems like it should be pretty simple but my searching hasn't turned anything up.

I have an array of objects that looks like this:

[{"A":4,"B":2},{"A":2,"B":1},{"A":3,"B":1},{"A":2,"B":1,"C":1}]

I want to flatten it down to something that looks like this (what I would think of as a reduce function):

{"A": 11, "B": 5, "C": 1}

The starting array of objects is the product of the transformation of a much larger and more complex starting object. The important detail is that the keys themselves are of arbitrary values (i.e. you might see 'D's and 'E's but the code itself needs to be blind to this). I've gotten to this point using Underscore.js and I'm hoping to find similarly clean, functional-style solution.

1
  • You need to post your attempt(s) please. And given the features built-in with ES5 there is no need for underscore Commented Jan 22, 2020 at 21:54

1 Answer 1

1

Get the key/value pairs and update the sum.

var data = [{ A: 4, B: 2 }, { A: 2, B: 1 }, { A: 3, B: 1 }, { A: 2, B: 1, C: 1 }],
    result = data.reduce((r, o) => (Object.entries(o).forEach(([k, v]) => r[k] = (r[k] || 0) + v), r), {});

console.log(result);

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

3 Comments

Yeah, that'll do it. I had been wondering if it was going to require an inner for-each on the key sets. Thanks for the help!
Is there a reason (beyond code clarity) to pass in the initial value of '{ }' rather than starting the accumulator with the first element?
it follows the non mutating approach of the data. whithout startValue, the first object is mutated.

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.