HELP! Algorithm Scripting: Where do I Belong

LINK TO Challenge

Why does this solution work for all but these cases;
getIndexToIns([10, 20, 30, 40, 50], 35) should return 3 .
getIndexToIns([40, 60], 50) should return 1 .
getIndexToIns([2, 20, 10], 19) should return 2 .
getIndexToIns([2, 5, 10], 15) should return 3 .

  function getIndexToIns(arr, num) {
    let x = arr.sort(function(a,b){return a-b});
    console.log(x);
    let v,k;
    if(x.length >0){
    x.forEach( (e) => { 
      if (e<=num){
      k = x.indexOf(e);
    } 
    })
    }
  else {
    k = 0;
  }
    return k;
  }

  getIndexToIns([40, 60], 50);

  • Can you link the challenge here.
    Next time if you need a help from a challenge, you can use the Get Help button on the sidebar.
1 Like

Very useful, thanks a lot. Had not noticed that feature.
I have linked the challenge now.

1 Like

I think the best approach would be to add num to your array, then sort… then just find the indexOf num.

arr = arr.concat(num);
arr = arr.sort((a,b) => a - b)
num =  arr.indexOf(num);
1 Like

thanks, i got it now