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 婆婆高寿祝福语大全简短