Basic Algorithm Scripting - Where do I Belong

Tell us what’s happening:
I m using findIndex and it should give me a index but it is giving me values. Why?

Also i find myself struggling so much solving problems, any tips for gettimg better?

Your code so far

function getIndexToIns(arr, num) {
  let h = []
  for(let i = 0 ;i < arr.length; i++){
    if(arr[i] < num){

  function number(n){
    return n == 50


getIndexToIns([40, 60], 50);

Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/ Safari/537.36

Challenge: Basic Algorithm Scripting - Where do I Belong

Link to the challenge:

I think you might be making the solution more complicated than it needs to be. One of the first things you do is sort the array passed into the function. (By the way, you shouldn’t rely on the default sort but rather explicitly tell sort you want to sort by number. Look up on google how to do that). Assuming you do have the array sorted numerically in ascending order, for example [10, 20, 30, 40, 50] and I gave you the number 35, tell us how you would figure out where to put 35 in that array in plain English, no code. Just describe the process in your mind of how you would do it.

1 Like

Firstly, getIndexToIns doesn’t have a return value so it always returns undefined.

Second, you have the value 50 hardcoded into the solution, which wouldn’t work for other cases even if the logic was correct.

Let’s run through the code using the example getIndexToIns([40, 60], 50):

  1. Pass [40, 60] as arr and 50 as num.
  2. Create h, an empty array.
  3. arr gets sorted into [40, 60].
  4. Start for loop: i = 0; i < 2; i++
  5. Push 40 into h[40]
  6. if(40 < 50) evaluates to true
  7. Push 50 into h[40, 50]
  8. for loop: i = 1; i < 2
  9. Push 60 into h[40, 50, 60]
  10. if(60 < 50) evaluates to false
  11. end for loop
  12. Call findIndex on h[40, 50, 60], calling number on every element.
  13. 40 == 50false
  14. 50 == 50true
  15. h.findIndex returns 1.

That’s the right answer for this case, so why doesn’t it work for others? Take bbsmooth’s example with [10, 20, 30, 40, 50] and 35.

If we run through the for loop, 35 gets inserted right from the get-go because 10 is less than 35. Then, it happens again for 20 and 30 so our final array is [10, 35, 20, 35, 30, 35, 40, 50]!

The first occurrence of 35 is at index 1, so your function would return 1.

Whenever you find yourself struggling, break down your code like that and you can find exactly where things start going wrong; in this case, the if condition (arr[i] < num).

This is also why it helps to keep things simple so you can debug more quickly. There are faster ways of solving this problem that don’t involve using .push() to build a new array from scratch. I recommend reading further into array functions.

Hope this helps!

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.