The objective with this code is to insert a number in an array, which should be first sorted by ascending order. The code should return the index where that number belongs in the sorted array.
Simple enough, but the way this next example was solved, baffles me:
function getIndexToIns(arr, num) {
arr.sort(function(a, b) {
return a - b;
});
for (var a = 0; a < arr.length; a++) {
if (arr[a] >= num) return a;
}
return arr.length;
}
getIndexToIns([1028, 64, 16, 32, 8, 256, 128], 50);
This code works, but I can't understand why using return arr.length; at the end, results in that index we need. Shouldn't that give us the actual length of the complete aray? Why does it results in the index of the inserted number should be?
Thanks in advance!
Aucun commentaire:
Enregistrer un commentaire