เราต้องเขียนฟังก์ชัน JavaScript ที่รับอาร์เรย์ของตัวเลข ฟังก์ชันต้องสร้างอาร์เรย์ใหม่จากอาร์เรย์นำเข้า โดยสมาชิกแต่ละตัวในอาร์เรย์ใหม่คือจำนวนสมาชิกในอาร์เรย์เดิมที่มีค่าน้อยกว่าสมาชิกที่ตรงตำแหน่งนั้น
ตัวอย่าง
ถ้าอาร์เรย์นำเข้าคือ:
const arr = [2, 7, 3, 1, 56, 4, 7, 8];
อาร์เรย์ผลลัพธ์ควรเป็น:
const output = [1, 4, 2, 0, 7, 3, 4, 6];
ตัวอย่างโค้ด
const arr = [2, 7, 3, 1, 56, 4, 7, 8];
const smallerThanCurrent = (arr = []) => {
let { length } = arr;
let res = Array(length).fill(0);
for (let i = 0; i < length; i++) {
for (let j = 0; j < length; ++j) {
if (i != j && arr[i] > arr[j]) {
++res[i];
}
}
}
return res;
};
console.log(smallerThanCurrent(arr));
ผลลัพธ์
[1, 4, 2, 0, 7, 3, 4, 6]