Did I do it wrong?

Tell us what’s happening:
I saw the solutions and they’re very concise.
My solution is 24 lines of code (excluding 2 comments).

does that make me a bad programmer? and does my code work in general?


function getIndexToIns(arr, num) {
//sort
let newArr = [];
while(arr.length > 0){
  let smallestElement = arr[0];
  let indexOfSmallest = 0;
  for(let i = 0; i < arr.length; i++){
    if(arr[i] < smallestElement){
      smallestElement = arr[i];
      indexOfSmallest = i;
    }
  }
  newArr.push(smallestElement);
  arr.splice(indexOfSmallest,1);
}
//find the correct index to place num
let whereToInsert = 0;
for(let i= 0; i < newArr.length;i++){
  if(i== newArr.length-1 && num > newArr[i]){
    whereToInsert = newArr.length;
  }else if(newArr[i] < num && newArr[i+1] >= num){
      whereToInsert = i+1;
  }
}
return whereToInsert;
}

let x = getIndexToIns([5, 3, 20, 3], 5);
console.log(x);

Challenge: Where do I Belong

Link to the challenge:

We all write verbose and clumsy code when we start out, that doesn’t make you a bad programmer, only an unexperienced one. One “rule” of software development is: 1 make it work - 2 make it clean - 3 make it fast. What that means is - first make it work, even if it’s not the best code.

Your code does what it should, so step 1 is achieved. Now you could start refactoring.
The first part could be replaced with one line, if you use the .sort method instead of manually sorting with a while loop. It takes some time to get familiar with Array methods like .sort, .findIndex or .filter, so it’s perfectly fine to solve this with only if/else statements and loops.

The problem with this particular challenge is that the description implies that you should first sort the array. It takes some thinking (and an accidental bright moment) to realise that the description is misleading, it’s supposed to help you understand what the challenge wants, but you don’t have to actually sort the array. You only have to find the number of elements that are smaller than num.

1 Like