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;
};
can someone please help