0

I have a function which is expected to 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.

getIndexToIns([1,2,3,4], 1.5) should return 1 because 1.5 is greater than 1 (index 0), but less than 2 (index 1).

The code executes as expected except when these argument are passed to it

getIndexToIns([5, 3, 20, 3], 5); //should return 2 but return 0

getIndexToIns([2, 5, 10], 15); //should return 3 but return -1

getIndexToIns([], 1)); //should return 0 but return -1

Here's my code in JavaScript

function getIndexToIns(arr, num) {
  arr = arr.sort();
  for(let i in arr){
   if(num < arr[i]){
arr.splice(i,0,num);

   } 
  }
  return arr.indexOf(num);
}
opeolluwa
  • 96
  • 8
  • 1
    Why not just insert and then sort? - if you then want to know where it was inserted, look at the index of the inserted number – mplungjan Oct 01 '20 at 08:34
  • Are you aware that you are also changing the array? You even add `num` several times. That is probably not what you want. If you only want to return the theoretical index, it might be better to just iterate through the array and count the number of items that are smaller than `num`. The resulting number is the index. – str Oct 01 '20 at 08:35
  • @mplungjan, I tried ```function getIndexToIns(arr, num) { arr.push(num); arr.sort(); return arr.indexOf(num); }``` But I got these errors getIndexToIns([3, 10, 5], 3) should return 0. getIndexToIns([5, 3, 20, 3], 5) should return 2. getIndexToIns([2, 20, 10], 19) should return 2. getIndexToIns([2, 5, 10], 15) should return 3. – opeolluwa Oct 01 '20 at 09:39
  • `const getIndexToIns = num => { arr.push(num); arr.sort((a,b)=>a-b); return arr.indexOf(num);}` – mplungjan Oct 01 '20 at 09:41
  • Without changing the array: `const getIndexToIns = num => { let newArr = arr.slice(0); newArr.push(num); newArr.sort((a,b)=>a-b); return newArr.indexOf(num);}` – mplungjan Oct 01 '20 at 09:42
  • Without changing the array, you don't have to sort it. Just loop and count smaller values like this: `var getIndexToIns = (arr, num) => arr.reduce((acc, val) => val < num ? ++acc : acc, 0);` – str Oct 01 '20 at 09:46

0 Answers0