DEV Community

Randy Rivera
Randy Rivera

Posted on

Where In The Array A Number should Be Inserted By Order

function getIndexToIns(arr, num) {
  return num;
}

getIndexToIns([40, 60], 50);
Enter fullscreen mode Exit fullscreen mode
  • Return the lowest index at which a value (second argument) should be inserted into an array (first argument) once it has been sorted. The returned value should be a number.
  • For example, getIndexToIns([1,2,3,4], 1.5) should return 1 because it is greater than 1 (index 0), but less than 2 (index 1).

  • Answer:

function getIndexToIns(arr, num) {
  arr.sort(function(a, b) {
    return a - b;
  });

  for (let i = 0; i < arr.length; i++) {
    if (arr[i] >= num) return i;
  }

  return arr.length;
}

getIndexToIns([40, 60], 50); // will display [40, 50, 60]
Enter fullscreen mode Exit fullscreen mode

Explanation:

  • First I sort the array using .sort(callbackFunction) to sort it by lowest to highest, from left to right.
  • Then I use a for loop to compare the items in the array starting from the smallest one. When an item on the array is greater than the number we are comparing against, then we return the index as an integer.

Top comments (0)