user2949793
user2949793

Reputation:

Call Objects all at once into Function returning a specific calculation with each of them?

How can I call each object of var auto without a explicit way?

I mean without having to write each of them in the function-call, in the speedAverage function and the return for calculating the average.

function Car (model, speed) {
    this.model = model;
    this.speed = speed;
}


var speedAverage = function(car1, car2, car3) {
    return (car1.speed + car2.speed + car3.speed)/ veh.length;
};



var auto = [
new Car("BMW", 220),
new Car("Ford", 260),
new Car("DeLorean", 350)
];

console.log("The average between these cars is " + speedAverage(auto[0], auto[1], 
auto[2]));

Thanks.

Upvotes: 0

Views: 54

Answers (4)

HBP
HBP

Reputation: 16043

Since you already have all your data in the auto array use the reduce function :

console.log (auto.reduce (
   function (speed, car) { 
     return speed + car.speed; 
   }, 0) / auto.length);

The call to reduce returns the sum of the speeds of all the cars in auto, divide that divided by the number of cars gives you the average.

Upvotes: 0

David Hellsing
David Hellsing

Reputation: 108500

Add a static function to Car and push the speed in the constructor, then you don’t have to do the auto thing:

var speeds = [];
function Car (model, speed) {
    this.model = model;
    this.speed = speed;
    speeds.push(speed);
}

Car.getAverageSpeed = function() {
  return eval(speeds.join('+'))/speeds.length;
};

new Car("BMW", 220),
new Car("Ford", 260),
new Car("DeLorean", 350)

console.log("The average between these cars is " + Car.getAverageSpeed());

Or you can use arguments and apply() like this:

var speedAverage = function() {
    return eval(Array.prototype.map.call(arguments, function(s) {
        return s.speed;
    }).join('+'))/arguments.length;
};

var auto = [
    new Car("BMW", 220),
    new Car("Ford", 260),
    new Car("DeLorean", 350)
];

console.log("The average between these cars is " + speedAverage.apply(0, auto));

Upvotes: 0

odedsh
odedsh

Reputation: 2624

I think you want to pass the array object to the function:

var speedAverage = function (arr) {
  var sum=0
  for(var i=0; i<arr.length; i++) {
     sum += arr[i];
  }
  return sum/arr.length;
}

and call it with speedAverage (auto)

you can also read about arguments if you are looking for functions with variable number of arguments.

Upvotes: 0

lonesomeday
lonesomeday

Reputation: 237975

You can do this very easily with the apply method. This function is used to call a function with the contents of an array as the parameters:

speedAverage.apply(null, auto);

Upvotes: 2

Related Questions