Home > Enterprise >  Javascript, sorting a numerical array above greater than zero
Javascript, sorting a numerical array above greater than zero

Time:01-05

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.

CodePudding user response:

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);

CodePudding user response:

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);

  •  Tags:  
  • Related