-1
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 :)

  • 1
    no, a value stores no reference to the variable it is assigned to. You could however use an object and then access the keys – pilchard Jan 19 '23 at 16:58
  • 2
    You don't want variables, you want properties of an object. e.g.: `sports = { cricket: [ "dhoni", ... ], football: [ CR7", ... ] }` Then you can access `sports[sportname]` where `sportname` is the string name of the property you want to access (the name of the sport like `cricket` or `football`). – Wyck Jan 19 '23 at 17:00
  • duplicates [JavaScript: Get Argument Value and NAME of Passed Variable](https://stackoverflow.com/questions/1009911/javascript-get-argument-value-and-name-of-passed-variable) and [Determine original name of variable after its passed to a function](https://stackoverflow.com/questions/3404057/determine-original-name-of-variable-after-its-passed-to-a-function) – pilchard Jan 19 '23 at 17:22
  • Does this answer your question? [How to get the original variable name of variable passed to a function](https://stackoverflow.com/questions/2749796/how-to-get-the-original-variable-name-of-variable-passed-to-a-function) – vimuth Jan 20 '23 at 06:43

1 Answers1

0

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");
mykaf
  • 1,034
  • 1
  • 9
  • 12
  • The answer to the question *'Is it possible to print the name of the variable alone that holds my array'* is no, but there are alternatives to achieve the OPs end goal. – pilchard Jan 19 '23 at 17:20