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
广告