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

111
Visualizações
How do you sort an array by only using specific elements?

I'm using an array as a temporary inventory (as part of a game). There are items and values, each being a string. They are always followed.

The value or quantity determines how much of that item you have.

For example: inventoryArray = ['bananas', '5', 'berries', '8', 'apples','3']

In the example above you would have a banana with a quantity of 5

My goal is to sort the array by quantity. So a function could return ['berries', '8','bananas', '5' 'apples','3']

Thanks!

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

0

As others have pointed out, this seems like A Bad Idea™ and you really should consider using a more suitable data structure.

Having said that, there are ways to do it.

In the snippet below I first convert the array to an object via reduce so you end up with a structure like this (which you should consider using in the first place):

{
  bananas: 5,
  berries: 8,
  apples: 3
}

I then sort that object's entries, producing a sorted array of pairs:

[
  ['apples', 3],
  ['bananas', 5],
  ['berries', 8],
]

Finally, flattening that array produces the result you're after:

['apples', 3, 'bananas', 5, 'berries', 8]

Again, I agree with the comments above suggesting that this calls for a more suitable data structure, but if you have to do it this way for some reason you could.

const inventoryArray = ['bananas', '5', 'berries', '8', 'apples','3']

const quantities = inventoryArray.reduce((acc, item, index, arr) => {
  // skip odd indices (the quantities)
  if (index % 2 === 1) {
    return acc;
  }
  
  // add the product and qty (index + 1) to the result
  return {
    ...acc,
    [item]: Number(arr[index + 1])
  }
}, {});

// sort the key value pairs
const arr = Object.entries(quantities).sort(([, qtyA], [, qtyB]) => qtyA - qtyB);

console.log(arr.flat());

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