JavaScript Return the lowest index at which a value should be inserted into an array once it has been sorted (either in ascending or descending order).


We have to write a function that returns the lowest index at which a value (second argument) should be inserted into an array (first argument) once it has been sorted (either in ascending or descending order). The returned value should be a number.

For example, Let’s say, we have a function 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).

Likewise,

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).

Therefore, let’s write the code for this function −

Example

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,));

Output

The output in the console will be −

1
2

Updated on: 26-Aug-2020

100 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements