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