-4

I want to randomize the results from the person array. How do I connect it to the if statement so it randomizes the person each time, and if I load it it gives me a different sentence each time.

let placea = 'Shopping Mall'
let placeb = 'Library'

let person = ['John', 'Sam', 'Ryan', 'Liam', 'David']

if (person === 'John' || person === 'Liam' || person === 'Sam') {
  console.log(`Lets go to the ${placea}`)
} else {
  console.log(`I love quiet places, lets go to the ${placeb}`)
}
John Kugelman
  • 349,597
  • 67
  • 533
  • 578
  • 1
    Duplicate of [Get a random item from a JavaScript array](https://stackoverflow.com/questions/5915096/get-a-random-item-from-a-javascript-array) – Guy Incognito Dec 04 '20 at 18:10
  • "so it randomizes the person each time" <= "each time" implies repetition of some sort. It is unclear in your question where that repetition is. – Taplar Dec 04 '20 at 18:10

1 Answers1

1

I think you want "person" to refer to a random person from your array and not the array itself.

A good trick to remember is how to get a random element from an array a (works with any array that isn't empty):

const a = [1, 2, 3];
const randomElement = a[Math.floor(Math.random() * a.length)];

Math.random gives a random float from 0 to almost 1

multiply it by the array length to get a random float from 0 to almost array length

Math.floor chops the decimal off to get a random int from 0 to array length - 1

let placea = 'Shopping Mall'
let placeb = 'Library'

let people = ['John', 'Sam', 'Ryan', 'Liam', 'David'];
let person = people[Math.floor(Math.random() * people.length)];

if (person === 'John' || person === 'Liam' || person === 'Sam') {
  console.log(`Lets go to the ${placea}`)
} else {
  console.log(`I love quiet places, lets go to the ${placeb}`)
}
James
  • 20,957
  • 5
  • 26
  • 41