Keshav1007
Keshav1007

Reputation: 625

How to use Array.reduce()?

I have a JSON response like below:

[
{"name": "a", "data": [{"value":10,"id":1},{"value":20,"id":2}],
{"name": "b", "data": [{"value":10,"id":1},{"value":20,"id":2}],
{"name": "c", "data": [{"value":10,"id":1},{"value":20,"id":2}],
{"name": "d", "data": [{"value":10,"id":1},{"value":20,"id":2}],
{"name": "e", "data": [{"value":10,"id":1},{"value":20,"id":2}],
]

How to sum each "value" inside each element of data (column wise) and get the result like:

[{"name": "something", "data":[{"value":50,"id":1},{"value":100,"id":2}]

How to use array.reduce() for this or is there any other method to achieve the above result?

Upvotes: 0

Views: 135

Answers (5)

Ramya Ramanathan
Ramya Ramanathan

Reputation: 78

I believe your JSON data looks like what I've used in the below snippet. You could do this:

    a = [
    {"name": "a", "data": [{"value":10,"id":1},{"value":20,"id":2}]},
    {"name": "b", "data": [{"value":10,"id":1},{"value":20,"id":2}]},
    {"name": "c", "data": [{"value":10,"id":1},{"value":20,"id":2}]},
    {"name": "d", "data": [{"value":10,"id":1},{"value":20,"id":2}]},
    {"name": "e", "data": [{"value":10,"id":1},{"value":20,"id":2}]},
    ]
    
    let reducer = (accumulator, currValue) => {
            accumulator.name = "something";
        	for (let i = 0; i < accumulator.data.length; i++) {
        			accumulator.data[i].value += currValue.data[i].value;
            }
            return accumulator
        };

    // This will give the result you want:

    console.log(a.reduce(reducer));

The result will be:

{"name":"something","data":[{"value":50,"id":1},{"value":100,"id":2}]}

Upvotes: 0

ngChaitanya
ngChaitanya

Reputation: 435

Try out the following logic.

var series = [{"name": "a", "data": [{"value":10,"id":1},{"value":20,"id":2}]}, ... , ....]

var resultSeries = series.reduce((acc, cur) => {
    var result = {
        name: ‘Something’,
        data: []
    };
    var dataArray = acc.data.map((el, i) => {
        var curData = cur.data[i] || {};
        var sum = (el.value || 0) + (curData.value || 0);
        return {
            value: sum
        }
    });
    result.data = dataArray ;
    return result;
})

now resultSeries will hold

[{"name": "something", "data":[{"value":50,"id":1},{"value":100,"id":2}]

Upvotes: 2

Nikhil Aggarwal
Nikhil Aggarwal

Reputation: 28445

Use Array.reduce and Array.map

var arr =[{"name": "a", "data": [{"value":10,"id":1},{"value":20,"id":2}]},{"name": "b", "data": [{"value":10,"id":1},{"value":20,"id":2}]},{"name": "c", "data": [{"value":10,"id":1},{"value":20,"id":2}]},{"name": "d", "data": [{"value":10,"id":1},{"value":20,"id":2}]},{"name": "e", "data": [{"value":10,"id":1},{"value":20,"id":2}]}];

var result = {
   "name" : "something",
   "data" : arr.reduce((a,c) => { // reduces/merges 2 records of arr
      a.data.map((v, i) => { // add values for the 2 records (column wise)
        v.value = v.value + c.data[i].value;
        return v;
      });
      return a;
   })
};
console.log(result);

Upvotes: 0

Nina Scholz
Nina Scholz

Reputation: 386550

You could take an object as hash table for the id and sum the values.

var array = [{ name: "a", data: [{ value: 10, id: 1 }, { value: 20, id: 2 }] }, { name: "b", data: [{ value: 10, id: 1 }, { value: 20, id: 2 }] }, { name: "c", data: [{ value: 10, id: 1 }, { value: 20, id: 2 }] }, { name: "d", data: [{ value: 10, id: 1 }, { value: 20, id: 2 }] }, { name: "e", data: [{ value: 10, id: 1 }, { value: 20, id: 2 }] }],
    result = { name: 'something', data: Object.values(array.reduce((r, { data }) => {
        data.forEach(({ value, id }) => {
            r[id] = r[id] || { value: 0, id };
            r[id].value += value;
        });
        return r;
    }, Object.create(null))) };

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Upvotes: 1

Dishonered
Dishonered

Reputation: 8841

Try this code

<script>
 var numbers = [
{"name": "a", "data": [{"value":10,"id":1},{"value":20,"id":2}]},
{"name": "b", "data": [{"value":10,"id":1},{"value":20,"id":2}]},
{"name": "c", "data": [{"value":10,"id":1},{"value":20,"id":2}]},
{"name": "d", "data": [{"value":10,"id":1},{"value":20,"id":2}]},
{"name": "e", "data": [{"value":10,"id":1},{"value":20,"id":2}]},
];

function getSum(total, val) {
  total.data[0].value = total.data[0].value + val.data[0].value;
  total.data[1].value = total.data[1].value + val.data[1].value;
  return total;
 }
function myFunction(item) {
   document.getElementById("demo").innerHTML = 
  JSON.stringify(numbers.reduce(getSum));
}

This prints

Sum of numbers in array: {"name":"a","data":[{"value":50,"id":1},{"value":100,"id":2}]}

The code just adds the values on each iteration and updates the existing value.

Upvotes: 0

Related Questions