Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

112
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda