First sort the data and then distribute values into a new array, in zigzag order:
function spread(data) {
let n = data.length;
// First sort
let sorted = [...data].sort((a, b) => a - b);
// Then spread
let result = Array(n);
for (let i = 0, j = 0; j < n; i++, j += 2) {
result[i] = sorted[j + 1]; // zig...
result[n - 1 - i] = sorted[j]; // zag
}
return result;
}
// Demo
var data = [22, 1, 3, 70, 20, 60, 4, 10];
let result = spread(data);
console.log(result);
0
solved Rearrange array on javascript [duplicate]