Alternative Shuffle: เรียงอาร์เรย์จากน้อยไปมาก แล้วจัดใหม่เป็น: มากสุด, น้อยสุด, มากสุดอันดับ 2, น้อยสุดอันดับ 2, ...
ตัวอย่าง
Input: [11, 7, 9, 3, 5, 1, 13] Sorted: [1, 3, 5, 7, 9, 11, 13] 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);
for (let start = 0; start < array.length; start += 2) {
array.splice(start, 0, array.pop()); // นำตัวสุดท้าย (มากสุด) ใส่หน้า
}
return array;
};
console.log(alternateShuffle(arr));
การทำงาน
- คัดลอกและเรียงน้อยไปมาก
- วนลูปทีละ 2 (
start += 2) pop()นำตัวมากสุดออก แล้วsplice(start, 0, ...)ใส่ที่ตำแหน่ง start
ผลลัพธ์
[ 13, 1, 11, 3, 9, 5, 7 ]
หมายเหตุ: โค้ดต้นฉบับมี array.sort((a, b) => a-b) ซ้ำ 2 ครั้ง