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
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式語言
C++
C#
MongoDB
MySQL
Javascript
PHP