Where do I Belong why is wrong

Where do I Belong why is wrong
0.0 0

#1

Tell us what’s happening:

Your code so far


function getIndexToIns(arr, num) {
  // Find my place in this sorted array.
  return arr.concat(num).sort().indexOf(num)

    
}

getIndexToIns([40, 60], 50);

Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.87 Safari/537.36.

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


#2

.sort() by default sorts array elements as if they are strings, so it will sort numbers not by numeric value, but by their “dictionary order”. Sorting [3, 10, 5] this way gives you [10, 3, 5], not [3, 5, 10].

You’ll need to supply a function to the sort() method so that it sorts the numbers correctly. Any of these work:

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

or

.concat(...).sort((a, b) => a - b).indexOf(...);

More reading about .sort()


#3

another approach would be to first check if the num already exists array, then sort the array and return the index, if not push the num to array, sort and return the index

—solution----

function getIndexToIns(arr, num) {

  if(arr.indexOf(num) !== -1){
    arr.sort((x, y) => x > y);
    return num = arr.indexOf(num); 
  } else {
    arr.push(num);
    arr.sort((x, y) => x > y);
    return num = arr.indexOf(num); 
  }
}

getIndexToIns([40, 60], 50);

#4

Your code has been blurred out to avoid spoiling a full working solution for other campers who may not yet want to see a complete solution. In the future, try to give the OP hints/suggestions instead of just a full solution.

Thank you.