Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

จัดเรียงอาร์เรย์ด้วย reduce function - JavaScript

เราต้องเขียนฟังก์ชันจัดเรียงอาร์เรย์ตัวเลขโดยห้ามใช้ Array.prototype.sort() ต้องใช้ Array.prototype.reduce() แทน

ตัวอย่างอาร์เรย์:

const arr = [4, 56, 5, 3, 34, 37, 89, 57, 98];

ตัวอย่าง

โค้ดต่อไปนี้เป็นตัวอย่าง:

// เราจะเรียงอาร์เรย์นี้แต่
// ห้ามใช้ array sort function
// ห้ามใช้ลูปแบบดั้งเดิม
// ใช้ ES6 function reduce() แทน

const arr = [4, 56, 5, 3, 34, 37, 89, 57, 98];

const sortWithReduce = arr => {
  return arr.reduce((acc, val) => {
    let ind = 0;
    while(ind < arr.length && val < arr[ind]){
      ind++;
    }
    acc.splice(ind, 0, val);
    return acc;
  }, []);
};

console.log(sortWithReduce(arr));

ผลลัพธ์

จะแสดงผลในคอนโซลดังนี้:

[
  98, 57, 89, 37, 34,
  5, 56, 4, 3
]