0

I'm doing one of the freeCodeCamp' JavaScript course tasks and can't find the explanation why my code works for some of the given cases and does not work for others.

The exercise is:

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).

My code for this is:

function getIndexToIns(arr, num) {

  let newArray = [...arr, num].sort()
  let result = newArray.indexOf(num);
  return result;
}

And the code above outputs correct results for some of the cases (eg. getIndexToIns([10, 20, 30, 40, 50], 30) and incorrect results for other cases (eg. getIndexToIns([5, 3, 20, 3], 5).

I expected it to concatenate arr with num, sort it and then output the index of num, which is the case of this exercise. Can someone explain to me why it does not work?

j08691
  • 204,283
  • 31
  • 260
  • 272
asia
  • 13
  • 4
  • 1
    but what happens if there's already a same number? – IT goldman Nov 05 '22 at 21:19
  • I guess it comes down to how the challenge expects you to insert when the number to check already exists in the array. – Seblor Nov 05 '22 at 21:20
  • 1
    @KonradLinkowski yes! thank you :) I didn't know that .sort() sorts elements alphabetically instead of numerically. Now it works correctly. – asia Nov 05 '22 at 21:26

2 Answers2

0

function getIndexToIns(arr, num) {
  let newArray = [...arr, num].sort((a,b)=>a-b)
  let result = newArray.indexOf(num);
  return result;
}

console.log(getIndexToIns([5, 3, 20, 3], 5))
0

Array.prototype.sort sorts an array alphabetically.

  • [10, 20, 30, 40, 50]. In this case, the alphabetical order and the numeric order are the same.
  • [5, 3, 20, 3]. In this case, the alphabetical order is the following: [ 20, 3, 3, 5 ].

In order to make a successful numeric sorting you must add a comparator function as an argument.

function getIndexToIns(arr, num) {
 let newArray = [...arr, num].sort((a, z) => a - z);
 let result = newArray.indexOf(num);
 return result;
}
arialdev
  • 51
  • 2
  • 6