Home > Back-end >  Is it possible to print the name of the variable alone that holds my array, not the values of array?
Is it possible to print the name of the variable alone that holds my array, not the values of array?

Time:01-22

function favPlayers(arr){
    for(i=0;i<arr.length;i  )
       {
          console.log(arr[i]);
       }
    console.log() // output I want here is "These are my fav (sport name) players" according to the sports I've given as an input

}

var cricket = ["dhoni", "Virat", "sachin", "ponting", "steyn", "abd"]
var football = ["CR7", "messi", "bale", "mbappe", "haaland", "bruno"]

In this function, I need to print the variabe name of the array alone based on my input. like if I pass football as a paramtere in second console football must be printed out in the "sport name" area. eg my output should be ("These are my fav football players")

console.log("These are my favourite" arr "players"); I tried this but instead it prints all the players name again. Is there anyway to do this? please let me know. This is my first stack overflow query and I am learning javascript as a noobie so if my question explanationa and my english is not that good pardon me :)

CodePudding user response:

With a little rearranging, yes, this is possible. Use an Object and the sports names as keys:

function favPlayers(arrName){
    for(i=0;i<sports[arrName].length;i  )
       {
          console.log(sports[arrName][i]);
       }
    console.log(`These are my fav ${arrName} players`); // output I want here is "These are my fav (sport name) players" according to the sports I've given as an input

}

var sports = {
  cricket: ["dhoni", "Virat", "sachin", "ponting", "steyn", "abd"],
  football: ["CR7", "messi", "bale", "mbappe", "haaland", "bruno"]
}
favPlayers("football");

  • Related