Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

162
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!