1

I have an array of objects that looks like this:

[{"A_abs":4,"A_perc":2, "B_abs":4,"B_perc":2, ...},{"A_abs":4,"A_perc":2, "B_abs":4,"B_perc":2, ...},{"A_abs":4,"A_perc":2, "B_abs":4,"B_perc":2, ...},{"A_abs":4,"A_perc":2, "B_abs":4,"B_perc":2, ...}]

There can be up to n elements in each object, each one consists of a _perc and an _abs value. I want to reduce the array to only 1 entry and sum each _abs value, the _perc can be anything else, like "-".

An expected result would be:

{"A_abs": 16, "A_perc": "-" "B_abs": 16, "B_perc": "-"  "C_abs": x, "C_perc": "-", ...}

The solution of this question does not fully statisfy me because I don't know how to adapt the function to only sum the "_abs" values.

How to adapt this function to only sum the _abs values, regardles of how many entries the object has?

var data = [{"A_abs":4,"A_perc":2, "B_abs":4,"B_perc":2},{"A_abs":4,"A_perc":2, "B_abs":4,"B_perc":2},{"A_abs":4,"A_perc":2, "B_abs":4,"B_perc":2},{"A_abs":4,"A_perc":2, "B_abs":4,"B_perc":2}],
    result = data.reduce((r, o) => (Object.entries(o).forEach(([k, v]) => r[k] = (r[k] || 0) + v), r), {});

console.log(result);

5
  • What is the expected output? Do you want to sum up all the A_ABS? Commented Jun 8, 2022 at 12:21
  • I want to sum all _abs , ignoring the _perc values. Commented Jun 8, 2022 at 12:22
  • The final object will have all the _abs keys, for ex: a_abs, b_abs, c_abs etc and all of them would have same value i.e. their sum? Commented Jun 8, 2022 at 12:25
  • @SSM, correct, the final object should have all _abs and their sums Commented Jun 8, 2022 at 12:27
  • @toffler Please check the answer below probably it does what you need. Commented Jun 8, 2022 at 12:29

1 Answer 1

3

You can check if the key ends with _abs and only if it does you add the values else you simply assign a value of -.

const data = [
    { A_abs: 4, A_perc: 2, B_abs: 4, B_perc: 2 },
    { A_abs: 4, A_perc: 2, B_abs: 4, B_perc: 2 },
    { A_abs: 4, A_perc: 2, B_abs: 4, B_perc: 2 },
    { A_abs: 4, A_perc: 2, B_abs: 4, B_perc: 2 },
  ],
  result = data.reduce(
    (r, o) => (
      Object.entries(o).forEach(([k, v]) =>
        k.endsWith("_abs") ? (r[k] = (r[k] || 0) + v) : (r[k] = "-")
      ),
      r
    ),
    {}
  );

console.log(result);

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.