Where do I Belong: By generating another array

Hello,
https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-algorithm-scripting/where-do-i-belong
Because I’m not well followed the exercice instructions, I wanted to generate another array before get the index “i”. Thus I writed this code which works well :

function getIndexToIns(arr, num) {
  arr.sort(function (a, b) {
    return a - b;
  });
  let newArr = arr.slice(0);
  console.log(newArr)
  if (num > newArr[newArr.length-1] || arr.length === 0) {
    arr.push(num);
    return arr.indexOf(num);
  } else {
    for (let i = 0; i < newArr.length; i++) {
    if ( newArr[i] > num) {
      arr.splice(i, 0, num);
      console.log(arr)
      console.log(i);
      console.log(arr.indexOf(num))
      return arr.indexOf(num);
     } 
    }
   }
  }

I compared with the freecodecamp solution (I just added a “console.log(i)”):

function getIndexToIns(arr, num) {
  arr.sort((a, b) => a - b);

  for (let i = 0; i < arr.length; i++) {
    if (arr[i] >= num) {
      console.log(i)
      console.log(arr.indexOf(num))
      return i;
    }
      
  }

  return arr.length;
}

I have 2 questions:

  1. with freecodecamp solution:
    console.log(i) === 2
    console.log(arr.indexOf(num)) === 2

    But with my solution:
    console.log(i) === 3

Why ?

  1. Note that I didn’t put an “=” sign in the condition, but it still works.
if ( newArr[i] > num)

Why ?

if ( newArr[i] >= num) this works for you because your return value is
return arr.indexOf(num) which returns the index of the first element that matches what you are looking for.

The other approach is following the logic that all you want to do is find where num should be in a given array, and the where of it is defined as:
num belongs at the first index where the element is not less than num
so that is why it does this if ( newArr[i] >= num), but if you really wanted to you could equally do this if (!(arr[i] < num)), but that other way is more straightforward imo.

You do not want to do work outside of what is necessary as this will lead to less performant code, and you are creating an array, and using the splice method which should be avoided unless you really need it.

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