我需要代碼來對陣列進行排序,因此最高的數字首先出現,然后是最低的數字,然后回傳并排序左邊的最高數字,然后是左邊的最低數字。
例如: [ 1, 2, 3, 4 ] = [ 4, 1, 3, 2 ]
我嘗試過這種方式,但代碼僅限于陣列中的 4 個數字。- 如果陣列是 [ 1, 0, 0, 1 ] 它總是回傳 1 0 0 1; - 如果陣列只有一個(或沒有數字),則回傳 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 ]
我期待一種根據任何條件對陣列進行排序的方法
uj5u.com熱心網友回復:
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));
uj5u.com熱心網友回復:
對其進行正常排序,然后對其進行迭代并創建一個新陣列,其中每次迭代將專案推到后面,將專案推到前面。
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);
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/529178.html
下一篇:計算完成給定任務的最短時間
