เราต้องเขียนฟังก์ชันที่คืนค่าดัชนีต่ำสุดที่ค่า (อาร์กิวเมนต์ตัวที่สอง) ควรถูกแทรกเข้าไปในอาร์เรย์ (อาร์กิวเมนต์ตัวแรก) หลังจากที่จัดเรียงแล้ว (ไม่ว่าจะเป็น ascending หรือ descending) ค่าที่คืนต้องเป็นตัวเลข
ตัวอย่างเช่น สมมติว่าเรามีฟังก์ชัน getIndexToInsert():
getIndexToInsert([1,2,3,4], 1.5, 'asc') ควรคืน 1 เพราะมันมากกว่า 1 (ดัชนี 0) แต่น้อยกว่า 2 (ดัชนี 1)
เช่นกัน:
getIndexToInsert([20,3,5], 19, 'asc') ควรคืน 2 เพราะเมื่ออาร์เรย์จัดเรียง ascending จะเป็น [3,5,20] และ 19 น้อยกว่า 20 (ดัชนี 2) และมากกว่า 5 (ดัชนี 1)
มาเขียนโค้ดสำหรับฟังก์ชันนี้กัน:
ตัวอย่างโค้ด
const arr = [20, 3, 5];
const getIndexToInsert = (arr, element, order = 'asc') => {
const creds = arr.reduce((acc, val) => {
let { greater, smaller } = acc;
if (val < element) {
smaller++;
} else {
greater++;
}
return { greater, smaller };
}, {
greater: 0,
smaller: 0
});
return order === 'asc' ? creds.smaller : creds.greater;
};
console.log(getIndexToInsert(arr, 19, 'des'));
console.log(getIndexToInsert(arr, 19));
ผลลัพธ์
ผลลัพธ์ในคอนโซลจะเป็นดังนี้:
1 2