JavaScript 中的替代洗牌

javascriptweb developmentfront end technologyobject oriented programming更新于 2025/12/19 13:32:17

替代洗牌

JavaScript 中的替代洗牌数组是一个数字数组,其中数字的索引方式是最大数字后面跟着最小元素,第二大元素后面跟着第二小元素,依此类推。

例如:如果输入数组是 −

const arr = [11, 7, 9, 3, 5, 1, 13];

那么输出应该是 &minus

const output = [13, 1, 11, 3, 9, 5, 7];

示例

以下是代码 −

const arr = [11, 7, 9, 3, 5, 1, 13];
const sorter = (a, b) => a - b;
const alternateShuffle = (arr) => {
   const array = arr
   .slice()
   .sort(sorter);
   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(alternateShuffle(arr));

输出

这将在控制台中产生以下输出 −

[
   13, 1, 11, 3,
   9, 5,  7
]

相关文章


有用资源