Whats this doing i don't understand it
royalgreen50 (0)

this for my class in freeCodeCamp. I copied it from their hint cause I don't understand what it is they want. Now I don't what it is doing.

   return a-b;

  for (var a=0; a<arr.length;a++){
    if (arr[a] >=num)
    return a;
  return arr.length;

getIndexToIns([40, 60], 50);

/*Return the lowest index at which a value (second argument) should be inserted into an array (first argument) once it has been sorted. The returned value should be a number.

For example, getIndexToIns([1,2,3,4], 1.5) should return 1 because it is greater than 1 (index 0), but less than 2 (index 1).

Likewise, getIndexToIns([20,3,5], 19) should return 2 because once the array has been sorted it will look like [3,5,20] and 19 is less than 20 (index 2) and greater than 5 (index 1).

Remember to use Read-Search-Ask if you get stuck. Write your own code.*/```
You are viewing a single comment. View All
malvoliothegood (182)

You need to create the getIndexToIns function. It needs to have two parameters: the array and the number whose index position in the sorted array is to be found. It is to return the index position that the number will be at if it was inserted into the array.

So, the function needs to first sort the array, and then find the position. The first lot of code will do this e.g.

function getIndexToIns(array, number) {
    // Sort the array in numerically increasing order
    array.sort(function(a, b) {	   
	   return a - b;
    // Rest of code ...


The "rest of code ..." is the second lot of code that uses the for loop to find the correct index value that number would be inserted at such that the number on its right (if it exists) is greater than or equal to it.

Note that there are two return statements. This is because the second one will be reached if the value of number is greater than the value of the highest number in the array. In this case the length of the array is returned because in this case number would be added to the right-hand end of the array.

If you have trouble completing the function let me know in a reply and I will show you the complete code.