Tell us what’s happening:
I dont know why my code isnt worcking. what did i missed?
Your code so far
function getIndexToIns(arr, num) {
arr.sort();
for (let i = 0; i < arr.length; i++) {
if (num < arr[i]) {
return [i];
}
}
}
getIndexToIns([40, 82, 65, 22, 17, 18, 60], 50);
//trier l'array du plus petit au plus grand
//créer une boucle qui passe dans l'array
//comparer num à chaque item, et push num dans l'array quand il rencontre plus grand que lui
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:69.0) Gecko/20100101 Firefox/69.0.
You are returning an array that has a value of i with index 0. Array is an object. You have to return a number. So, you have to return just an i instead of [i].
Ok so i worcked quite a long time on the solution, and i ended up with something that worck:
function getIndexToIns(arr, num) {
arr.sort(function(a, b) {return a-b});
for (let i = 0; i < arr.length || arr.length == 0; i++) {
if (num <= arr[i]) {
return i;
}else if (num > Math.max(...arr)) {
return arr.length;
}
}
}
console.log(getIndexToIns([], 1));
getIndexToIns([2, 5, 10], 15);
Though, i have 2 questions:
i tried to put || arr.length == 0 in my else if statement, but it doesnt worcked, so i tried to put it in my for, and bingo, but i dont really know why. Someone has the answer to this?
Im not forced to insert an “else” statement after an if, and / or an else if?
You don’t need the ||, you can shorten up with <=, like: i <= arr.length. But you need <= because in the case of
console.log(getIndexToIns([], 1));
arr equals 0. So you need to check to deal with the case that arr equals 0. If you don’t, when you have ([], 1), arr equals zero and your for loop won’t execute.
You don’t need a “else” statement after an “if” statement. But in your case you nested the else statement within the for loop (which is also why you needed to use i <= arr.length). It could be done with two “if” statements, and in the example below you don’t need to check if arr equals 0.
function getIndexToIns(arr, num) {
// Find my place in this sorted array.
arr.sort(function(a, b) {return a-b});
for (let i = 0; i < arr.length; i++) {
if (num <= arr[i]) {
return i;
}
};
if (num > Math.max(...arr)) {
return arr.length;
}
};
console.log(getIndexToIns([], 1)); // logs 0