Where do I Belong task (SPOILER)

Tell us what’s happening:
Describe your issue in detail here.

  **Your code so far**

function getIndexToIns(arr, num) {

arr.unshift(num);
arr.sort(function(a, b) {
  return a - b;
});
   let indArr = arr.indexOf(num);
    return indArr;  
}

getIndexToIns([40, 60], 50);

Hey,
so ive managed to pass this task but none of the solutions match( or are even close) to mine and I was looking for some feedback as to whether I’m using code that i really shouldnt.
Many thanks in advance

  **Your browser information:**

User Agent is: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.77 Safari/537.36

Challenge: Where do I Belong

Link to the challenge:

I’ve added spoiler tags to your code.

1 Like

I checked the sample solutions, and although, they may not be exactly the same as yours, some of them have the same idea (algorithm) as yours, namely add the num to the array and sort it.

The main issue I have with the approach is that the passed array gets modified. In general, this behavior is something we want to avoid. If I call your function like

let xs = [40, 60]
getIndexToIns(xs, 50);

then xs is [40,50,60] after the call. To avoid modifying the passed array, you could create a copy and then work on the copy.

Another approach that requires no sorting is to simply count the number of values that are smaller than num.

1 Like

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