0

i'm trying to load 4 random cities every time the main page loads using useEffect() hook and i am subtracting the items i already found to avoid duplications so i wrote this function :

const cities = [
  { id: "0", name: "New York" },
  { id: "1", name: "California" },
  { id: "2", name: "Tokyo" },
  { id: "3", name: "Paris" },
  { id: "4", name: "Oran" },
  { id: "5", name: "roma" },
  { id: "6", name: "dubai" },
  { id: "7", name: "madrid" },
  { id: "8", name: "beijing" },
  { id: "9", name: "montreal" }
];

const randomCitiesLoader = () => {
  let randomCities = [];
  randomCities.push(cities[Math.floor(Math.random() * cities.length - 1)]);
  for (let i = 0; i < 3; i++) {
    let queryCities = cities.filter(city => {
      return !randomCities.find(item => {
        return item.id === city.id;
      });
    });
    randomCities.push(
      queryCities[Math.floor(Math.random() * queryCities.length - 1)]
    );
  }
  return randomCities;
};

but i'm getting this error : enter image description here

can someone please help

mr rogers
  • 3,200
  • 1
  • 19
  • 31
Yacine Bouziane
  • 208
  • 2
  • 14

1 Answers1

1

Math.floor(Math.random()*cities.length-1) can be -1 so you can push undefined to resulting array because cities[-1] is undefined.

You best option would be to use array[Math.floor(Math.random()*array.length)] to pick random element from array.

Yury Tarabanko
  • 44,270
  • 9
  • 84
  • 98