JavaScript返回排序值(升序或降序)后应在数组中插入的最低索引。
我们必须编写一个函数,该函数返回将值(第二个参数)排序(升序或降序)后应在数组(第一个参数)中插入的最低索引。返回的值应该是一个数字。
例如,假设我们有一个函数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
热门推荐
10 圣诞祝福语简短小学
11 祖国七十华诞简短祝福语
12 老师送的祝福语简短
13 生日祝福语大全女生简短
14 祝女性生日祝福语简短
15 牛年女神节祝福语简短
16 情人表白祝福语简短大气
17 老公开业祝福语简短
18 官宣新年祝福语简短