JavaScript 返回对数组进行排序(升序或降序)后应将值插入到数组中的最低索引。

javascriptweb developmentobject oriented programming更新于 2025/10/13 0:12:17

我们必须编写一个函数,返回对数组进行排序(升序或降序)后应将值(第二个参数)插入到数组(第一个参数)中的最低索引。返回值应该是一个数字。

例如,假设我们有一个函数 getIndexToInsert() −

getIndexToInsert([1,2,3,4], 1.5, ‘asc’) 应该返回 1,因为它大于 1(索引 0),但小于 2(索引 1)。

同样,

getIndexToInsert([20,3,5], 19, ‘asc’) 应该返回 2,因为一旦数组按升序排序,它看起来就会像 [3,5,20],而 19 小于 20(索引 2)且大于 5(索引 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

相关文章


有用资源