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

更新時間: 26-8-2020

140 次瀏覽

開啟你的職業生涯

完成課程,獲得認證

開始
廣告
© . All rights reserved.