Why does my solution not work?

Tell us what’s happening:
For this challenge I have to return the index position where num would fit in the sorted array.

I’m trying to incorporate the indexOf method in my solution, but what I’m coming up with isn’t working and I’d like some help with figuring out why. To explain my thinking process, I wanted to first create a variable that contained the sorted array from least to greatest. Then create a variable to contain the index where num will go. So I created a For loop to index through the sorted array, and tried to return the indexOf sortedArr[i] that is greater than num.

EDIT 1: I just realized the first problem was having the For loop condition set to i > sortedArr.length which means it would never execute. I changed that and now its saying sortedArr[i].indexOf is not a function, which I’m working to resolve.

  **Your code so far**

function getIndexToIns(arr, num) {
let sortedArr = arr.sort();
let greaterThanIndex = 0;
for (let i = 0; i < sortedArr.length; i++) {
return greaterThanIndex = sortedArr[i].indexOf(sortedArr[i] > num)
} return greaterThanIndex

console.log(getIndexToIns([40, 60, 80, 20, 10, 11], 50))
  **Your browser information:**

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.141 Safari/537.36.

Challenge: Where do I Belong

Link to the challenge:

The first return statement inside your for loop is only going to let the for loop iterate one time and the the function is exited. That is one problem.

Another problem the first argument passed to indexOf specifies the value you are looking for in the array. You are going to either be passing true or false to it (which is probably not what you want to do). The reason you are passing true or false, is the sortedArr[i] > num is the argument which will evaluate to either true or false.

I think I understand this, it only iterates the loop one time because of the return statement, which does not execute multiple times. So I should just remove the “return”.
I also understand why the argument will produce a true/false value but I’m not sure what I should put in there instead. Any pointers?

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