FCC: "Where do I belong" without sorting

Hi everyone,

In the challenge “[Where I belong](link: https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-algorithm-scripting/where-do-i-belong)” , it is required to return the index that a given element will have in an array after it has been sorted.

In solutions that I’ve seen the array is first sorted and than the element is compared with the content of the array until it reach his position.

I think it migth pretty inefficient because sorting the array is useless, you can find the index by directly comparing the element you have to add with every item in the array and every time you find an item that is lower than your element you add 1 to a counter. When you reach the end the value of the counter is the index you have to find.

The code I’ve created is:

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

Anyone has anything to say about this topic or has some suggestion to make?

Best regards,
Paolo Carlevero - Italy

I added spoiler tags since your solution works.

I think that your solution is basically the approach used in the second solution on the hints page: freeCodeCamp Challenge Guide: Where do I Belong

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