我们需要编写一个函数,比如说minMax()要接受一个Numbers数组并重新排列元素,使得最大的元素首先出现,然后是最小的元素,然后是第二个最大的元素,然后是第二个最小的元素,依此类推。
例如-
// if the input array is: const input = [1, 2, 3, 4, 5, 6, 7] //那么输出应该是: 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 ]