Where do I Belong - JavaScript Solution & Walkthrough
(14/16) Learn how to solve coding challenges using FreeCodeCamp's curriculum.
14/16 Where do I Belong
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).
function getIndexToIns(arr, num) {
return num;
}
getIndexToIns([40, 60], 50);
Credit: FreeCodeCamp.org
Understanding the Challenge
For this challenge, you are to complete the getIndexToIn
function. This function takes an array arr
as first argument and a number num
as second argument.
Your task is to find the lowest possible index num
at which num can be insert into the array when it has been sorted. We are provided with 2 examples in the problem description.
Pseudocode
Given an array and an index number
Update the array by inserting the number into the arry
Sort the updated array
Find the index of the number in the sorted array
return the index of the number.
Solving the Challenge
First, we need to update the arr
by adding num
to it. To add an element to an array, we can use the .push()
method. This will add the number to the end of the array.
arr.push(num)
console.log(arr) // [ 40, 60, 50 ]
In the given example, the initial array is [40, 60]. Using the .push()
method adds num
which is 50 to the end of the array.
Next, we sort the array. We are not told specifically in challenge description how the sorting is to be done. However, looking at test cases provided, all of them were sorted in ascending order. Thus, its safe to assume that the function should do the sorting in ascending order.
We can use the .sort()
method to sort the array as follows;
arr.sort((a, b) => a - b)
console.log(arr) // [40, 50, 60]
We can now use the indexOf()
method to find the index of num
. We'll save the results in a variable. Let's call the variable indexOfNum
.
const indexOfNum = arr.indexOf(num)
console.log(indexOfNum) // 1
Finally we return indexOfNum
. Our function is now complete.
return index(indexOfNum)
Final Solution
function getIndexToIns(arr, num) {
arr.push(num)
arr.sort((a, b) => a - b)
const indexOfNum = arr.indexOf(num)
return indexOfNum;
}
getIndexToIns([40, 60], 50); // 1
Congratulations!
You just cracked the 14th challenge in this series.
Cheers and happy coding!