1

I have an array of movies objects with the properties: movieName, grade, and position. For example these objects look like:

var movies = [ { movieName: "bee movie", grade: 3, position 1},
               { movieName: "Shrek", grade: 5, position: 2} ];

I want to get the movieName property of an object. To decide which object from the movies array I want the movieName from I create a variable named arrayPosition which is a random number between 0 and the length of the array - 1:

arrayPosition = Math.floor(Math.random() * movies.length );

For example:

var movies = [{
    movieName: "Incredibles",
    grade: 4,
    position: 1
  },
  {
    movieName: "Bolt",
    grade: 5,
    position: 2
  }
];

const arrayPosition = Math.floor(Math.random() * movies.length);

console.log(movies[arrayPosition].movieName);

In this case I would like it to console either "Incredibles" or "Bolt" depending on if arrayPosition is 0 or 1 but it only consoles undefined.

I have seen solutions to similar problems but in those cases the position of the object in the array was not a variable but a decided number. For some reason this difference make it not work. How do I get only the movieName property from an object in the array?

3
  • it should console.log correctly either 0 or 1 index Commented Feb 15, 2020 at 8:54
  • Apart from not declaring arrayPosition it looks correct, why not make your code above into a working snippet? Commented Feb 15, 2020 at 8:57
  • what is the problem you are facing? Your code looks correct to me. Commented Feb 15, 2020 at 20:16

1 Answer 1

2

Your example code works correctly.

var movies = [
  { movieName: "bee movie", grade: 3, position: 1},
  { movieName: "Shrek", grade: 5, position: 2},
  { movieName: "Incredibles", grade: 4, position: 1}, 
  { movieName: "Bolt", grade: 5, position: 2}
];

var arrayPosition = Math.floor(Math.random() * movies.length)
console.log(movies[arrayPosition].movieName)

If you knew that you always wanted to console.log the title of the 2nd movie in the array, you could instead do:

var movies = [
  { movieName: "bee movie", grade: 3, position: 1},
  { movieName: "Shrek", grade: 5, position: 2},
  { movieName: "Incredibles", grade: 4, position: 1}, 
  { movieName: "Bolt", grade: 5, position: 2}
];

var arrayPosition = 1

console.log(movies[arrayPosition].movieName)

Remember that:

JavaScript arrays are zero-indexed: the first element of an array is at index 0, and the last element is at the index equal to the value of the array's length property minus 1.

Using an invalid index number returns undefined.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.