Ashley
Ashley

Reputation: 27

sum of multidimensional array javascript

I want to perform the sum operation on each subarray using javascript using forEach,map,reduce function, so that ultimately my output should look like:

sum = [8,13,22]

but I am not getting the desired output. Please assist where I am going wrong.Thanks.

var Data = [{"a":1,"b":2,"c":5},{"a":3,"b":4,"c":6},{"a":6,"b":7,"c":9}];
var newArr = [];
Data.forEach(function(item) { 
  item = item.reduce(function(a, b) {
    return a + b;
  });
  newArr.push([item]);
});
console.log(newArr);

Upvotes: 0

Views: 155

Answers (2)

Nina Scholz
Nina Scholz

Reputation: 386519

You could map the summed values, literately.

var data = [{ a: 1, b: 2, c: 5 }, { a: 3, b: 4, c: 6 }, { a: 6, b: 7, c: 9 }],
    result = data.map(o => Object.values(o).reduce((a, b) => a + b));

console.log(result);


Just some annotation to the given code:

You can not iterate an object with reduce, because that works only for array. To overcome this problem, you need just the values of the object by taking Object.values and then, you could iterate the values.

Then return the sum without wrapping it in an array.

var Data = [{"a":1,"b":2,"c":5},{"a":3,"b":4,"c":6},{"a":6,"b":7,"c":9}];
var newArr = [];
Data.forEach(function(item) { 
    var sum = Object.values(item).reduce(function(a, b) {
        return a + b;
    });
    newArr.push(sum);
});

console.log(newArr);

A better solution would be the use of Array#map, because you need one value for each element of the array.

var data = [{"a":1,"b":2,"c":5},{"a":3,"b":4,"c":6},{"a":6,"b":7,"c":9}];
    newArr = data.map(function(item) { 
        return Object.values(item).reduce(function(a, b) {
            return a + b;
        });
    });

console.log(newArr);

Upvotes: 4

Dipak Telangre
Dipak Telangre

Reputation: 1993

As per your example, Old way

var Data = [{"a":1,"b":2,"c":5},{"a":3,"b":4,"c":6},{"a":6,"b":7,"c":9}];
var newArr = [];
Data.forEach(function(object) {
  let sum = 0;
  for (var property in object) {
    if (object.hasOwnProperty(property)) {
        sum += object[property]
    }
 }
  newArr.push(sum);
});
console.log(newArr);

Upvotes: 0

Related Questions