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

149
Visualizações
How to push object keys to an array multiple times based on their integer values in JavaScript

I've looked on several sites including through the suggested answers when posting this question, so forgive me if it's been answered elsewhere. I'm very new to JavaScript (and coding in general). I'm working on a 'weighted lottery' project and I have an approach in mind that I'm sure will work, but am stuck on a particular point.

I have an object which contains the outcomes as object keys and the number of times that particular outcome will be produced as the object values of integer type. Specifically, this:

const weights = {
  'win': 5,
  'loss': 10,
  'tie': 3
}

I want to push the object keys to an array called 'outcomes' multiple times based on their associated value. For the example above, it would result in an array that lists 'win' 5 times, 'loss' 10 times and 'tie' 3 times.

I have come across the .fill method, but it doesn't seem to work in a situation like this, where I want the number of object items to be dynamic (both in the number of them and their values - i.e. having 15 different 'outcomes' each with different values assigned to them).

Any pointers? Thanks all for this wonderful resource!

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

0

fill could be used for this, but I think I'd just use loops:

const outcomes = [];
for (const [key, count] of Object.entries(weights)) {
    for (let n = count; n > 0; --n) {
        outcomes.push(key);
    }
}

Live Example:

const weights = {
    "win": 5,
    "loss": 10,
    "tie": 3
};

const outcomes = [];
for (const [key, count] of Object.entries(weights)) {
    for (let n = count; n > 0; --n) {
        outcomes.push(key);
    }
}
console.log(outcomes);

But here's how you might use fill along with spread if you wanted to:

const outcomes = [];
for (const [key, count] of Object.entries(weights)) {
    outcomes.push(...Array.from({length: count}).fill(key));
}

Live Example:

const weights = {
    "win": 5,
    "loss": 10,
    "tie": 3
};

const outcomes = [];
for (const [key, count] of Object.entries(weights)) {
    outcomes.push(...Array.from({length: count}).fill(key));
}
console.log(outcomes);

David's answer points to a better way to do the fill than that (I'd forgotten about start and end, doh!), but I would do it slightly differently:

const outcomes = [];
for (const [key, count] of Object.entries(weights)) {
    const start = outcomes.length;
    outcomes.length += count;
    outcomes.fill(key, start, outcomes.length);
}

Live Example:

const weights = {
    "win": 5,
    "loss": 10,
    "tie": 3
};

const outcomes = [];
for (const [key, count] of Object.entries(weights)) {
    const start = outcomes.length;
    outcomes.length += count;
    outcomes.fill(key, start, outcomes.length);
}
console.log(outcomes);

That said, the advantage of David's answer is you're telling the JavaScript engine up-front how many elements the array will have, which can be used for optimization. It doesn't often matter, and probably doesn't matter here, but still, it's there.

about 4 years ago · Juan Pablo Isaza Relatório

0

You can do it with fill. You can create a new Array with the combined weights as the length parameter and then fill it like so.

const weights = {
  'win': 5,
  'loss': 10,
  'tie': 3
};

let outcomes = new Array(Object.values(weights).reduce((value, initial) => value+initial));
let pos = 0;
for(let [key, value] of Object.entries(weights))
{
  outcomes.fill(key, pos, pos += value);
}

console.log(outcomes);

about 4 years ago · Juan Pablo Isaza Relatório

0

Maybe this will be helpful:

const weights = {
  win: 5,
  loss: 10,
  tie: 3
}

const result = []

Object.keys(weights).forEach(name => {
  const times = weights[name]
  result.push(...new Array(times).fill(name))
})

console.log(res)
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