使用 JavaScript 重新排列陣列以達到最大最小形式


我們要求編寫一個函式,例如 minMax(),它接收一個數字陣列,並重新排列元素,使最大的元素排在後面,其次是第二大的元素,其次是第二小的元素,依此類推。

例如 −

// if the input array is:
const input = [1, 2, 3, 4, 5, 6, 7]
// then the output should be:
const output = [7, 1, 6, 2, 5, 3, 4]

因此,讓我們為此函式編寫完整程式碼 −

示例

const input = [1, 2, 3, 4, 5, 6, 7];
const minMax = arr => {
   const array = arr.slice();
   array.sort((a, b) => a-b);
   for(let start = 0; start < array.length; start += 2){
      array.splice(start, 0, array.pop());
   }
   return array;
};
console.log(minMax(input));

輸出

控制檯中的輸出為 −

[
   7, 1, 6, 2,
   5, 3, 4
]

更新於: 26-8 月-2020

222 次瀏覽

啟動您的職業生涯

完成該課程並獲得認證

開始
廣告
© . All rights reserved.