Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

210
Visualizações
Reset randomization after it goes through all the items in the array

I'm learning JS and I just finished a project, here the code:

const menu = {
    _meal: "",
    _price: 0,
    //Let set the new value of meal only if it's a string.
    set meal(mealToCheck) {
        if (typeof mealToCheck === "string") {
            return this._meal = mealToCheck;
        }
    },
    //Let set the new value of price only if it's a number.
    set price(priceToCheck) {
        if (typeof priceToCheck === "number") {
            return this._price = priceToCheck;
        }
    },
    //If both setters are true, then return a message using them, otherwise return message saying the values are wrong.
    get todaysSpecial() {
        if (this._meal && this._price) {
            return `Today's Special is ${this._meal}, for just ${this._price}£!!`;
        } else {
            return "Meal and Price wasn't entered correctly!!";
        }
    }
};

//Arrays for the meal options and respective prices, also a constant to get a random number in the array range.
const meals = ["Pizza", "Steak", "Pie", "Roast", "Moussaka", "Lasagne", "Tacos"];
const prices = [/*Pizza*/9, /*Steak*/13, /*Pie*/11, /*Roast*/14, /*Moussaka*/9, /*Lasagne*/10, /*Tacos*/9];
const random = Math.floor(Math.random() * meals.length);

//Assigns a new random value from the arrays. I used a single randomizer so that you can combine a plate to its price by the index number.
menu.meal = meals[random];
menu.price = prices[random];

//Check if the number of items in the meals and prices array it's equal, and if it is, creates the menu of the day string.
if (meals.length === prices.length) {
    console.log(menu.todaysSpecial);
} else {
    console.log("The number of prices and meals don't match!!");
}

At the end of the code I added a couple of arrays and a Math.random so that every time I run it, it gives me a different value.

Now I'm trying to find a way to have the random value give unique values until it reaches the array length, and then restart. At the moment I have 7 items in the array simulating the day of the week, I'd like to have each item coming out once per week and then reset.

I know how to do it by following the array index order, but I can't come out with a way to do it randomly, any input?

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

You can combine your prices and meals array to make it a bit simpler, then shuffle it.

const menu = {
  _meal: "",
  _price: 0,
  //Let set the new value of meal only if it's a string.
  set meal(mealToCheck) {
    if (typeof mealToCheck === "string") {
      return (this._meal = mealToCheck);
    }
  },
  //Let set the new value of price only if it's a number.
  set price(priceToCheck) {
    if (typeof priceToCheck === "number") {
      return (this._price = priceToCheck);
    }
  },
  //If both setters are true, then return a message using them, otherwise return message saying the values are wrong.
  get todaysSpecial() {
    if (this._meal && this._price) {
      return `Today's Special is ${this._meal}, for just ${this._price}£!!`;
    } else {
      return "Meal and Price wasn't entered correctly!!";
    }
  }
};

//Arrays for the meal options and respective prices, also a constant to get a random number in the array range.
let meals = [
  { name: "Pizza", price: 9 },
  { name: "Steak", price: 13 },
  { name: "Pie", price: 11 },
  { name: "Roast", price: 14 },
  { name: "Moussaka", price: 9 },
  { name: "Lasagne", price: 10 },
  { name: "Tacos", price: 9 }
];

// Used to shuffle your meals array
function shuffle(array) {
  let currentIndex = array.length,
    randomIndex;

  // While there remain elements to shuffle.
  while (currentIndex != 0) {
    // Pick a remaining element.
    randomIndex = Math.floor(Math.random() * currentIndex);
    currentIndex--;

    // And swap it with the current element.
    [array[currentIndex], array[randomIndex]] = [
      array[randomIndex],
      array[currentIndex]
    ];
  }

  return array;
}

meals = shuffle(meals);

// Iterate meals
for (let i = 0; i < meals.length; i++) {
  menu.meal = meals[i].name;
  menu.price = meals[i].price;
  console.log(menu.todaysSpecial);
}
about 4 years ago · Juan Pablo Isaza Relatório

0

It is easy every time you pick value from the array remove it and when the array end just reset the array to the initial value For not having probleme with rand nomber it should be like this Rand=Math.random()*array.lenght;

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda