Hello,
https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-algorithm-scripting/where-do-i-belong
Because I’m not well followed the exercice instructions, I wanted to generate another array before get the index “i”. Thus I writed this code which works well :
function getIndexToIns(arr, num) {
arr.sort(function (a, b) {
return a - b;
});
let newArr = arr.slice(0);
console.log(newArr)
if (num > newArr[newArr.length-1] || arr.length === 0) {
arr.push(num);
return arr.indexOf(num);
} else {
for (let i = 0; i < newArr.length; i++) {
if ( newArr[i] > num) {
arr.splice(i, 0, num);
console.log(arr)
console.log(i);
console.log(arr.indexOf(num))
return arr.indexOf(num);
}
}
}
}
I compared with the freecodecamp solution (I just added a “console.log(i)”):
function getIndexToIns(arr, num) {
arr.sort((a, b) => a - b);
for (let i = 0; i < arr.length; i++) {
if (arr[i] >= num) {
console.log(i)
console.log(arr.indexOf(num))
return i;
}
}
return arr.length;
}
I have 2 questions:
-
with freecodecamp solution:
console.log(i) === 2
console.log(arr.indexOf(num)) === 2But with my solution:
console.log(i) === 3
Why ?
- Note that I didn’t put an “=” sign in the condition, but it still works.
if ( newArr[i] > num)
Why ?