0

I have a function which gives three objects

function myfunc(one, two, three){
    this.one = one;
    this.two = two;
    this.three = three;
}

var a = new myfunc(6,5,7);
var b = new myfunc(10,4,2);
var c = new mufunc(20,1,8);

This gives the three separate objects which are useful. However, i want to create a forth object which is the sum of a,b and c. In effect this would be the same as:

var all = new myfunc(36, 10, 17); 

I can do this manually:

aa = a.one + b.one + c.one
bb = a.two + b.two + c.two
cc = a.three + b.three + c.three

var all = new myfunc(aa, bb, cc)

but is there a better way which is less manual.

2
  • 1
    No, there is no other way since each object knows nothing about the others. Commented Jul 22, 2019 at 10:42
  • Is it possible to add the the three variables together in one equation / function? Commented Jul 22, 2019 at 10:43

3 Answers 3

3

You could put them into an array and sum their properties in a loop of course:

var list = [a, b, c];
function sum(arr, prop) {
    return arr.reduce((acc, x) => acc+x[prop], 0);
}
var all = new myfunc(sum(list, "one"), sum(list, "two"), sum(list, "three"));

Alternatively, mutate an initially empty instance in a loop:

var all = [a, b, c].reduce((obj, x) => {
    obj.one += x.one;
    obj.two += x.two;
    obj.three += x.three;
    return obj;
}, new myfunc(0, 0, 0));
Sign up to request clarification or add additional context in comments.

1 Comment

Very nice solution!
1

The only way to achieve this is to create a function to handle this for you, if you're going to be running it regularly. Just pass in the objects and the function will handle it:

function sum_objects( obj1, obj2, obj3 )
{
  return new myfunc(
    (obj1.one + obj2.one + obj3.one),
    (obj1.two + obj2.two + obj3.two),
    (obj1.three + obj2.three + obj3.three)
  );
}

Comments

-2
function myfunc(one, two, three){
    this.one = one;
    this.two = two;
    this.three = three;
}

myfunc.prototype.add = function(){
    return this.one + this.two + this.three
}

var all = new myfunc(36, 10, 17);
all.add()

2 Comments

That adds the properties of the same object together, not the same property of three objects together.
Furthermore, that returns a number, not another myfunc object.

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.