How is the code, and can you propose some improvements?

function getIndexToIns(arr, num) {
  let myArr = [...arr];
  myArr.sort((a, b) => a-b);
  for (let i = 0; i < myArr.length; i++) {
    if (num === myArr[i]) { return i;}
    else if (num > myArr[i] && num < myArr[i+1]) {
      return i+1;
    }
  }
  if (arr.length === 0) {
    return 0;
  } else {
    return arr.length;
  }

}

How is the code, and can you propose some improvements? And thank you in advance!

Link to the challenge ( Basic Algorithm Scripting: Where do I Belong) : https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-algorithm-scripting/where-do-i-belong

The important thing is your code works. Well done! I solved this differently than you did, but your way is just as valid.

At this point, in my opinion, it’s fine to just be happy with solving the algorithm. It can be useful to come back to the basic algorithms and redo them in a few weeks, or a month. Refactoring your code on your own after learning more is great practice.

Oh, by the way, you should probably use the spoiler function when posting full solutions. They don’t like too many solutions for the challenges in the forum.

1 Like

This would be a good candidate for a ternary expression.

This challenge can be solved without sorting first. Think about an algorithm to do that. I will give you a hint:

If you iterate through the array and find that no other number is smaller than num, then you know you would insert num at the beginning of the array (index 0).

If you iterate through the array and find that only one of the elements is smaller than num, then you know you would insert num as the second element (index 1).

If you iterate through the array and fine that two elements are smaller than num, you know you would insert num as the third element (index 2).

See a pattern yet?

1 Like

Do you mean like that? :

function getIndexToIns(arr, num) {
  let myArr = [...arr];
  
  if (arr.length === 0) {
    return 0;
  } else {
    let n = 0;
    for (let i=0; i<myArr.length; i++) {
      if (num > myArr[i]) {
        n++;
      }
    }
    return n;
  }

}

Nice algorithmic approach btw, i didn’t though of it!

yes, good job!

you could simplify it a lot tho

  • you don’t need to copy the array as you are not making changes to it
  • you don’t need the early return for length of 0, as in that case the loop wouldn’t execute and n stay at 0, so 0 is returned anyway
1 Like