[Question]JS methods inside class

Joined
Mar 27, 2023
Messages
1
Reaction score
0
JavaScript:
class Vehicle{
   constructor(cpName,model)
    {
        this.cpName    = cpName;
        this.model      = model;
        this.totalKm    = 0;
        this.available  = true;
        this.travels    = [];
    }
    totalTravel = () =>{
      
    }
}
now i am stuck on the method it needs to go through the this.travels array and sum up the totalKm and update this.travels how can i do that ???
 
Joined
Mar 31, 2023
Messages
95
Reaction score
8
To calculate the totalKm by iterating over the travels array and updating the totalKm value of the object, you can define the totalTravel method in the Vehicle class like this:
JavaScript:
class Vehicle {
  constructor(cpName, model) {
    this.cpName = cpName;
    this.model = model;
    this.totalKm = 0;
    this.available = true;
    this.travels = [];
  }
  totalTravel = () => {
    this.totalKm = this.travels.reduce((acc, travel) => {
      return acc + travel.km;
    }, 0);
  };
}
In this code, the reduce() method is used to iterate over the travels array and sum up the km property of each object. The reduce() method takes two arguments: the first is a callback function that executes on each element of the array, and the second is the initial value of the accumulator (0 in this case).

Once the totalKm value is calculated, you can access it by calling the totalTravel method on a Vehicle object. For example:
JavaScript:
const myVehicle = new Vehicle("MyCompany", "MyModel");
myVehicle.travels.push({ km: 10 });
myVehicle.travels.push({ km: 20 });
myVehicle.totalTravel();
console.log(myVehicle.totalKm); // Output: 30
This code creates a new Vehicle object and adds two travel objects to its travels array. It then calls the totalTravel method on the myVehicle object to calculate the totalKm value, which is logged to the console.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top