I am new to JavaScript and am currently completing the part of the course called Basic Scripting having a lot of struggle in understanding why my solutions don’t work. Could someone please take a look at the code and explain why the code i wrote is not passing for the exercise? Thank in advance!
So the condition for the exercise was:
Blockquote 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 return1
because it is greater than1
(index 0), but less than2
(index 1).
Likewise,getIndexToIns([20,3,5], 19)
should return2
because once the array has been sorted it will look like[3,5,20]
and19
is less than20
(index 2) and greater than5
(index 1).
I wrote the code:
function getIndexToIns(arr, num) {
arr.sort();
for (let i = 0; i < arr.length; i++) {
if (arr[i] >= num) return i;
}
return arr.length;
}
getIndexToIns([40, 60], 50);
Since the sort method is already built into Java Script as long as i googled, but the correct version of this code is this:
function getIndexToIns(arr, num) {
arr.sort((a, b) => a - b);
for (let i = 0; i < arr.length; i++) {
if (arr[i] >= num) return i;
}
return arr.length;
}
getIndexToIns([40, 60], 50);
Could someone please explain me why?