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

164
Visualizações
How to split an Array of Objects into another Arrays based on their values?

I need to separate the data from an Array depending on the player-id. The database I've got looks like this:

var database =[
 {
  player: 1,
  level: 1,
  score: 20
 },
 {
  player: 2,
  level: 1,
  score: 25
 },
 {
  player: 3,
  level: 1,
  score: 7
 },
 {
  player: 1,
  level: 2,
  score: 25
 },
 {
  player: 2,
  level: 2,
  score: 7
 }
]

Little by little, new objects containing new players will be added and old objects will disappear, as the database is limited to 40 entries. This means that the database changes dynamically.

My goal is to push the objects into new Arrays depending on the player-id. So the result has to look like this:

var player1 = [
 {
  player: 1,
  level: 1,
  score: 20
 },
 {
  player: 1,
  level: 2,
  score: 25
 }
]

var player2 = [
 {
  player: 2,
  level: 1,
  score: 25
 },
 {
  player: 2,
  level: 2,
  score: 7
 }
]

var player3 = [
 {
  player: 3,
  level: 1,
  score: 7
 }
]
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

First, you can convert the array to an object to improve the access and then you can assign object properties to variables:

const database = [
 {
  player: 1,
  level: 1,
  score: 20
 },
 {
  player: 2,
  level: 1,
  score: 25
 },
 {
  player: 3,
  level: 1,
  score: 7
 },
 {
  player: 1,
  level: 2,
  score: 25
 },
 {
  player: 2,
  level: 2,
  score: 7
 }
];

const { player1, player2, player3 } = database.reduce((acc, el) => {
  if (!('player' + el.player in acc)) acc['player' + el.player] = [el];
  else acc['player' + el.player].push(el);
  return acc
}, {});

console.log(player1, player2, player3);

about 4 years ago · Juan Pablo Isaza Relatório

0

Although it's possible to create global variables with dynamic names, it's not possible to create non-global variables with dynamic names, and the global environment is already sufficiently crowded that creating a bunch of new globals is not best practice.

Instead, use a Map:

const playerArrays = new Map();
for (const entry of database) {
    const key = `player${entry.player}`;
    const array = playerArrays.get(key);
    if (!array ) {
        // Haven't seen this one yet, add a new array
        playerArrays.set(key, [entry]);
    } else {
        // We have the array, add to it
        array.push(entry);
    }
}

Then you get an individual array by using playerArrays.get("player1") and such.

Live Example:

var database = [{
    player: 1,
    level: 1,
    score: 20
  },
  {
    player: 2,
    level: 1,
    score: 25
  },
  {
    player: 3,
    level: 1,
    score: 7
  },
  {
    player: 1,
    level: 2,
    score: 25
  },
  {
    player: 2,
    level: 2,
    score: 7
  }
];

const playerArrays = new Map();
for (const entry of database) {
    const key = `player${entry.player}`;
    const array = playerArrays.get(key);
    if (!array ) {
        // Haven't seen this one yet, add a new array
        playerArrays.set(key, [entry]);
    } else {
        // We have the array, add to it
        array.push(entry);
    }
}
console.log("player1:", playerArrays.get("player1"));
.as-console-wrapper {
    max-height: 100% !important;
}

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