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

174
Vistas
Javascript, sorting a numerical array above greater than zero

Please can anyone help me. I am able to sort an array into either ascending or descending order but I want to be able to sort the array above a numeric value.

For example if I have an array:

a0 = new Array(8, 1, 3, 9, 0, 0, 0, 0);
// Sort a0 to end up with;
// 1, 3, 8, 9, 0, 0, 0, 0;

I have included a fiddle: Basic template

I can only get it to work but with the zeros at the front of the sorted array

// 0, 0, 0, 0, 1, 3, 8, 9;

Thanks.

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

Just write a custom comparator function for the Array.prototype.sort function that ensures that 0 will be sorted last:

const a0 = new Array(8, 1, 3, 9, 0, 0, 0, 0);

a0.sort((a, b) => {
  if (a === 0) return 1;
  if (b === 0) return -1;
  return a - b;
});

console.log(a0);

about 4 years ago · Juan Pablo Isaza Denunciar

0

You could sort zeros with a check of being not zero and move this values to bottom.

const array = [8, 1, 3, 9, 0, 0, 0, 0];

array.sort((a, b) => !a - !b || a - b);

console.log(...array);

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