0

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.

6
  • 1
    sort can take a compare function to evaluate the values to sort to ensure the correct the sort order: [8, 1, 3, 9, 0, 0, 0, 0].sort((a, b) => a > 0? a - b : +Infinity ).
    – RobG
    Commented Jan 4, 2022 at 21:18
  • Could you edit the question to add clarity around what "sort the array above a numeric value" means?
    – Andy Ray
    Commented Jan 4, 2022 at 21:18
  • @RobG your function doesn't give the correct result.
    – jefi
    Commented Jan 4, 2022 at 21:41
  • @jefi—it returns [1, 3, 8, 9, 0, 0, 0, 0], which is what the OP asked for. If there are other requirements, the OP needs to state them. Anyway, it's just an example of a sort function that fits the OP.
    – RobG
    Commented Jan 4, 2022 at 21:57
  • Sorry but I get [ 0, 0, 0, 0, 1, 3, 8, 9 ] as result of console.log([8, 1, 3, 9, 0, 0, 0, 0].sort((a, b) => a > 0? a - b : +Infinity ))
    – jefi
    Commented Jan 4, 2022 at 22:01

2 Answers 2

2

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

1

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

4
  • All right! Now it is working!
    – jefi
    Commented Jan 4, 2022 at 21:39
  • This effectively just filters out 0 and puts it at the end, values less than 0 are sorted normally. a === 0 should probably be a <= 0 etc. ;-)
    – RobG
    Commented Jan 4, 2022 at 22:19
  • @RobG This produces the result OP wanted: unless we get more information on how OP wants to handle negative numbers.
    – Terry
    Commented Jan 4, 2022 at 22:41
  • "either ascending or descending order … able to sort the array above a numeric value." It misses on both those criteria. But it's on the right track. :-)
    – RobG
    Commented Jan 4, 2022 at 23:03

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.