Home > Net >  Pass an array of objects into another class
Pass an array of objects into another class

Time:04-06

let's suppose I have a class:

class Intern{
        constructor(name, mark) {
    this.name = name
    this.mark = mark
  }
    getMark() {return mark}
}

 let a = new Intern('John', 10) // let's say I create 3 objects of this class
 let b = new Intern('Marry', 9) 
 let c = new Intern('Anne', 8)

How I can pass an array of Interns as an argument to another class Mentor? I can create an empty array and do like this:

arr = []
 
Mentor{
   constructor(name, arr){
   this.name
   this.arr
  }
  getMentorHappiness() = this.arr.Intern.mark * 2 
}

Is that correct? So in dependent-ion on which mentor I select it will show me the only the get happiness method of these interns that only this Mentor teaches. Something like that:

let d = new Mentor('Dean', [Anne, John]
let e = new Mentor('Sam', [Marry])

I think I have to refer somehow to the info based on the Mentors array of objects input?

CodePudding user response:

Few things here:

  1. you forgot mentor is a class ( class Mentor )
  2. forgot to assign values from constructor
  3. forgot to return the value from getMentorHappiness function
  4. you need to pass an array with interns to the Mentor constructor, not an empty one
  5. you need then to address the intern array somehow to get the mark from it
  6. forgot to reference this. in Intern's mark to return

Below is the example of refactored your code, that works

class Intern{
    constructor(name, mark) {
    this.name = name;
    this.mark = mark;
  }
  getMark() {return this.mark;}
}

class Mentor{
    constructor(name, arr) {
    this.name = name;
    this.arr = arr;
  }
  getMentorHappiness() {
    let sum = 0; 
    for (let intern of this.arr) { 
      sum  = intern.getMark();
    } 
    return sum / this.arr.length * 2 
  }
}

// driver code to test
let a = new Intern('John', 10);
let b = new Intern('Marry', 9);
let c = new Intern('Anne', 8);

let d = new Mentor('Dean', [a, b, c]);

console.log(d.getMentorHappiness());
console.log(a.getMark());
console.log(d.arr[0].getMark());

This function will calculate average for the Interns for the specific mentor. Please note it's multiplied by 2 as in the original question

  • Related