Home > Software engineering >  I am trying to access elements of this multidimensional array and getting strange results like : �
I am trying to access elements of this multidimensional array and getting strange results like : �

Time:01-05

  let BestAlbumsByGenre = [];
    BestAlbumsByGenre [0]  = "Country";
    BestAlbumsByGenre [0][0] = "Johnny Cash : Live at Folsom Prison";
    BestAlbumsByGenre [0][1] = "Patsy Cline : Sentimentally Yours";
    BestAlbumsByGenre [0][2] = "Hank Williams : I'm Blue Inside";
    BestAlbumsByGenre [1] = "Rock";
    BestAlbumsByGenre [1][0] = "T-Rex : Slider";
    BestAlbumsByGenre [1][1] = "Nirvana : Nevermind";
    BestAlbumsByGenre [1][2] = "Lou Reed : Transformer";
    BestAlbumsByGenre [2] = "Punk";
    BestAlbumsByGenre [2][0] = "Flipper : Generic";
    BestAlbumsByGenre [2][1] = "The Dead Milkmen";
    BestAlbumsByGenre [2][2] = "Patti Smith : Easter";
    
  console.log(BestAlbumsByGenre[0][1]);

this is my code.

If I want to access the BestAlbumsByGenre[0][1], it should return "Patsy Cline : Sentimentally Yours"; But it's returning the character 'o', maybe it's returning the 2nd character of 0th element, String "Country", but if it so then why? thanks in advance.

CodePudding user response:

After BestAlbumsByGenre [0] = "Country", which sets a string as 0th entry in the array, BestAlbumsByGenre [0][0] = "Johnny Cash : Live at Folsom Prison" has no effect any more. BestAlbumsByGenre[0][1] returns the 1st character in that string.

Consider a different data structure, for example:

BestAlbumsByGenre[0] = {Genre: "Country", Albums: []};
BestAlbumsByGenre[0].Albums[0] = "Johnny Cash : Live at Folsom Prison";

CodePudding user response:

I don't think you understand multidimensional array structures in javascript at all. Does this example make their structure clearer?

let BestAlbumsByGenre = [];
BestAlbumsByGenre[0] = [
  "Country", // 0 0
  [ // 0 1
    "Johnny Cash : Live at Folsom Prison", // 0 1 0
    "Patsy Cline : Sentimentally Yours", // 0 1 1
    "Hank Williams : I'm Blue Inside" // 0 1 2
  ]
]; //etc...

console.log(BestAlbumsByGenre[0][0]);  //Country
console.log(BestAlbumsByGenre[0][1][1]); //Patsy Cline : Sentimentally Yours
  • Related