Where do I Belong - Why isn't this code working

I have been scratching my head to find out why if the second not being placed via slice into the first element which is an array.

Is there an issue with


arr[row].splice(col+1,0,num);

?

i used col + 1 since from my understanding, the element to be added would be before that element. col on it’s own would lead to num being placed before col which means the order from smallest to largest won’t be implemented

Your code so far

function getIndexToIns(arr, num) {
  arr.sort(function (a, b) { return a - b });
  for (var row = 0; row < arr.length; row++) {
    for (var col = 0; col < arr[row].length; col++) {
      if (num > arr[row][col]) {
        arr[row].splice(col + 1, 0, num);
      }
    }
  }
  return arr;
}

getIndexToIns([40, 60], 50);

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36.

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-algorithm-scripting/where-do-i-belong/

I don’t get why you are looping inside your array as if it was 2 dimmensional. There is only one row.

Also, your function doesn’t return anything.

Oh that is right, sorry. I didn’t scroll all the way :sweat_smile:
Thanks.

return arr[row].indexOf(num);

The above would return the required index right?

Okay so splice is used here when the if condition is met.

I.E. when inputted num is bigger than an element in the array, splice is used to place num after that element. That way, we end up with an array where num is placed in the correct index such that the array lists elements from smallest to largest

Got it

function getIndexToIns(arr, num) {
let newArr = arr.slice();


for (var index = 0 ; index<arr.length ; index++) {

if (num>arr[index]) {
newArr.splice(index+1,0,num);
break;
}



}

newArr.sort( (function(a,b) {return a-b} ) );

  return newArr.indexOf(num);
}

The only part that’s stopping me from completing this is

getIndexToIns([], 1) should return 0.

Tried using an if statement i.e

if (arr = []) {
  return 0;
}

But even though this resolves [] should return 0, it causes many of the other tests to no longer output the index of num…

Thank you

In practice, which is better

Sort the initial array first, then add the new element
vs
add the new element then sort the array

I did the latter arbitrarily, any recommendation if one exists?