Sort an array as [1st highest number, 1st lowest number, 2nd highest number, 2nd lowest number...]

454 Views Asked by At

I need the code to sort the array so the highest number comes first, then the lowest number, then go back and sort the highest number left and then the lowest number left.

ex: [ 1, 2, 3, 4 ] = [ 4, 1, 3, 2 ]

I tried this way, but the code is limited to only 4 numbers in the array. -if the array is [ 1, 0, 0, 1 ] it always returns 1 0 0 1; -if the array is just one (or no number) it returns Infinity.

let m = [ ]

const max = Math.max.apply(null, m);
const min = Math.min.apply(null, m);
const max2 = Math.max.apply(null, m.filter(ma2 => ma2 < max));
const min2 = Math.min.apply(null, m.filter(mi2 => mi2 > min));

console.log(max, min, max2, min2)
// If m = [ 1, 2, 3, 4 ] the output is [ 4, 1, 3, 2 ]
// but things go wrong if m = [ 1, 0, 0, 1] or [ 1, 2, 3, 4, 5] or simply [ 5 ]

I was expcting a way to sort the array according to any condition

2

There are 2 best solutions below

0
CertainPerformance On BEST ANSWER

Sort it normally, then iterate over it and create a new array, where each iteration pushes the item at the back and the item at the front.

const m = [1, 2, 3, 4];
m.sort((a, b) => a - b); // if not already sorted

const sorted = [];
while (m.length) {
  sorted.push(m.pop());
  if (m.length) {
    sorted.push(m.shift());
  }
}
console.log(sorted);

0
Andrew Parks On

let m = [1, 2, 3, 4];
const f=m=>m.sort((a,b)=>b-a).map((_,i)=>m[~~(i%2?m.length-i/2:i/2)]);
console.log(f(m));