0

I have been stuck on this for a little while now, but I'm unsure on how I can flatten and reduce the below example data into unique key value pairs with the value being combined if there are multiples of the same key.

Example:

const data = [
  { test: 200 },
  { test2: 300, test3: 100 },
  { test3: 400, test4: 150, test2: 50 },
];

Expected result:

const result = [
    { test: 200 }, 
    { test2: 350 }, 
    { test3: 500 }, 
    { test4: 150 }
];

Any ideas?

TIA

1
  • @TannerDolby I guess its slightly related but Im still unsure on how to combine the values Commented Mar 9, 2022 at 22:55

1 Answer 1

1

Try this:

const data = [
  { test: 200 },
  { test2: 300, test3: 100 },
  { test3: 400, test4: 150, test2: 50 }
];

const flattenedAndReduced = data.reduce((prev, current) => {
  Object.keys(prev).forEach((key, index) => {
    if (current[key]) {
      prev[key] += current[key];
      delete current[key];
    }
  });
  Object.keys(current).forEach((key) => {
    if (!prev[key]) prev[key] = current[key];
  });
  return { ...prev };
});

const flattenedAndReducedToArray = Object.keys(flattenedAndReduced).map((key) => ({
  [key]: flattenedAndReduced[key]
}));

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

Comments

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.