我们需要编写一个JavaScript函数,该函数将Numbers数组作为唯一参数。
该函数应返回一个Numbers数组,其中包含的元素数小于原始数组中每个对应元素的元素数。
例如-
如果输入数组是-
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]