Where do I Belong (BUG)?

Where do I Belong (BUG)?
0.0 0

#1

I don’t get why i had this error: **

getIndexToIns([5, 3, 20, 3], 5) should return 2

**. i mean why would it return 2 if it returns an array [3,5,20] 5 is clearly on index 1

Your code so far


function getIndexToIns(arr, num) {
  // Find my place in this sorted array.
  arr.push(num); // push the num argument to the array
  arr.sort((a,b)=>a-b); // sort the array in ascending order
  let newset = [... new Set(arr)]; // create a new set that's free of duplicates and convert it to array
  function returnIndex(x){ // find the index of the array element that is equal to the num argument
    return x >= num;
  }
  return newset.findIndex(returnIndex);
}

getIndexToIns([5, 3, 20, 3], 5);

Your browser information:

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

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


#2

It’s not at index 1, because the array is sorted in ascending order: [3, 3, 5, 20]. 5 is at index 2

What you’re doing is removing duplicates, the challenge never asks you to do this, so you are getting the wrong index to insert (your array looks like [3,5,20])


#3

Yeah i’ve solve it by removing the newset and just use the old array cause i thought the problem requires the removal of duplicates,


#4

alternative solution

function getIndexToIns(arr, num) {
  arr.sort(function(a, b){return a-b});
  let i=0;
  while(num>arr[i]){
    i++;
  }
  return i;
}