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

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