0

I have following code snippet which should return all the team names of a agile team. But code returns undefined. I have already tried let _this = this; and replaced this with _this but no result. Can anyone help me with this please.

let teamSelector = {
  teams: ['Team Alpha', 'Team Beta', 'Team Delta'],
  selectTeam: function(members){
    // let _this = this; 
    return members.map((member)=>{
      return `${member} is on ${this.teams[Math.random() * 3]}`;
    });
  }
};

teamSelector.selectTeam(['Anna','Jhon','Kevin','Lesli']);
Steave Jones
  • 154
  • 1
  • 8

3 Answers3

1

Math.random() returns fractional numbers. If you want an array index you need integers

see Using bitwise OR 0 to floor a number

let teamSelector = {
  teams: ['Team Alpha', 'Team Beta', 'Team Delta'],
  selectTeam: function(members) {
    // let _this = this; 
    return members.map((member) => {
      return `${member} is on ${this.teams[Math.random() * 3 | 0]}`;
    });
  }
};

console.log(teamSelector.selectTeam(['Anna', 'Jhon', 'Kevin', 'Lesli']));
gman
  • 100,619
  • 31
  • 269
  • 393
1

You have to pass default 0 in math.random

let teamSelector = {
      teams: ['Team Alpha', 'Team Beta', 'Team Delta'],
      selectTeam: function(members){
        // let _this = this; 
        return members.map((member)=>{
          return `${member} is on ${this.teams[Math.random() * 3 | 0]}`;
        });
      }
    };

    teamSelector.selectTeam(['Anna','Jhon','Kevin','Lesli']);
Himanshu Pandey
  • 688
  • 2
  • 8
  • 15
0

The value generated from Math.random is a float number so it will never reference an array index from this.teams, hence undefined value.

What you need to do is generate a random number using Math.random() * this.teams.length so that it will never generate an index value larger than the array size itself. You then need to use Math.floor to round this down as your Math.random generates a float number.

let teamSelector = {
  teams: ["Team Alpha", "Team Beta", "Team Delta"],
  selectTeam: function (members) {
    return members.map((member) => 
    `${member} is on ${
        this.teams[Math.floor(Math.random() * this.teams.length)]
      }`
    );
  },
};

teamSelector.selectTeam(["Anna", "John", "Kevin", "Lesli"]);

Just a side note too - arrow functions implicitly return so you don't need to return inside the map. However you do need to use return for the map itself to keep the context of this inside the block scope of the object. You will see, if you implicitly return the map then this will reference the window object or a higher up block scope such as the class implementation.