เราต้องเขียนฟังก์ชันที่คืนค่าดัชนีต่ำสุดที่ควรแทรกค่า (อาร์กิวเมนต์ที่สอง) ลงในอาร์เรย์ (อาร์กิวเมนต์แรก) เมื่อจัดเรียงแล้ว (ไม่ว่าจะเรียงลำดับจากน้อยไปมาก) ค่าที่ส่งคืนควรเป็นตัวเลข
ตัวอย่างเช่น สมมติว่าเรามีฟังก์ชัน getIndexToInsert() −
getIndexToInsert([1,2,3,4], 1.5, ‘asc’) should return 1 because it is greater than 1 (index 0), but less than 2 (index 1).
เช่นเดียวกัน
getIndexToInsert([20,3,5], 19, ‘asc’) should return 2 because once the array has been sorted in ascending order it will look like [3,5,20] and 19 is less than 20 (index 2) and greater than 5 (index 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