This article is on the freeCodeCamp Basic Algorithm challenge “Where do I belong”.
The instructions are as thus:
“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).
Likewise, getIndexToIns([20,3,5], 19)
should return 2
because once the array has been sorted it will look like [3,5,20]
and 19
is less than 20
(index 2) and greater than 5
(index 1).”
The test conditions are:
getIndexToIns([10, 20, 30, 40, 50], 35)
should return 3
.
getIndexToIns([10, 20, 30, 40, 50], 30)
should return 2
.
getIndexToIns([40, 60], 50)
should return 1
.
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
.
Before we proceed, I‘ll advise the .sort()
array method be read, as well as understand how a for loop
and if statement
works in JavaScript as these would be employed in solving the challenge.
See Code below:
Steps
Step 1:
Declare the function getIndexToIns
and set parameters arr
and num
. Sort the argument of the parameter arr
from lowest to highest as stated in the instruction using Array.sort()
.
Step 2:
Create a for loop
to loop through the index position i
of the already sorted array arr
, and an if statement
where if the parameter num
is less than or equal to any array item arr[i]
looped through, return i
which is the index position of the particular array item (actually the first array item) larger than num
.
Step 3:
Exit the if statement
and for loop
, then return the length of the array arr
. This is done to ensure that any num
value larger than all the array arr
item values will be given an assumed last index (or last position) in the array which is equal to arr.length
.
Step 4:
Exit the function getIndexToIns
and call the function with its likely arguments for example, getIndexToIns([10,5,20,40,38],35)
Voila! Now we know where everyone belongs!
If this was helpful, kindly hit the heart below so others can see this!