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
CodePudding user response:
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);
CodePudding user response:
let m = [ 1, 2, 3, 4 ];
const f = m => [...m.sort((a,b)=>b-a), ...m.sort((a,b)=>a-b)].flatMap((e,i,a)=>[a[i],a[i a.length/2]]).slice(0, m.length);
console.log(f(m));