Viết hàm nhận mảng số, trả về mảng mới mà mỗi phần tử là số lượng phần tử trong mảng gốc nhỏ hơn phần tử tương ứng.
Ví dụ: [2,7,3,1,56,4,7,8] → [1,4,2,0,7,3,4,6].
Ví dụ
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));
Kết quả
[1, 4, 2, 0, 7, 3, 4, 6]