0

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);
1
  • What is the output that you desire? Commented Feb 8, 2018 at 19:08

2 Answers 2

4

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);

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

Comments

0

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);

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.