Tell us what’s happening:
Hello there, I’m currently stuck in the part where if the value of num is the largest value out of all elements in the array then I will have to return the index of the length of the array but somehow I cannot seem to get it right. I’m very new to JS so I don’t know many methods to use hence the long way for sorting the array.
function getIndexToIns(arr, num) {
if (arr.length === 0) {
return 0;
} else {
//SORTING
for (let i = 0; i < arr.length; i++) {
let temp = 0;
for (let j = i + 1; j < arr.length; j++) {
if(arr[j] < arr[i]){
temp = arr[j];
arr[j] = arr[i];
arr[i] = temp;
}
}
}
for (let j = 0; j < arr.length; j++) {
if (num <= arr[j]) {
return j;
}
}
}
}
getIndexToIns([40, 60], 50);
**Your browser information:**
User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.1.1 Safari/605.1.15
there is an easier logic to handle this challenge. The following isnt exactly a spoiler, but it will guide you to a way how to solve it easier, write a simpler code.
You dont really need to sort the array in order to find the place for a specific number. You can simply count the numbers which are lower than that number, which will tell you how many numbers you need to place in front of it, indirectly telling you at what position that number would go, if we were to sort them. (if all numbers are greater then the number, it will be placed in position zero, if only one number is lesser than the question number, we put it at second position, only one number would go ahead of it and so on).
Thanks for your tip, it took me way much longer to solve as my problem was that I wrote my return inside my for-loop (in the second attempt of code) where as it much a very simple condition using a counter.
Both my first and second attempt code works but the second attempt’s code is much simpler and cleaner. Thanks for your help again ^^
let tempArr = [...arr];
console.log(tempArr);
/*
FIRST ATTEMPT
if (tempArr.length === 0) {
return 0;
} else {
//SORTING
for (let i = 0; i < tempArr.length; i++) {
let temp = 0;
for (let j = i + 1; j < tempArr.length; j++) {
if(tempArr[j] < tempArr[i]){
temp = tempArr[j];
tempArr[j] = tempArr[i];
tempArr[i] = temp;
}
}
}
for (let j = 0; j < tempArr.length; j++) {
if (num <= tempArr[j]) {
return j;
} else if (num > tempArr[j] && j === tempArr.length - 1) {
return j + 1;
}
}
}
*/
// to count how many numbers is num bigger than
let counter = 0;
//if length of arr is 0 then return 0
if (tempArr.length === 0) {
return 0;
} else {
//check where to insert num
for (let i = 0; i < tempArr.length; i++) {
if (num > tempArr[i]) {
counter += 1;
}
console.log("i: " + i);
console.log("counter: " + counter);
}
return counter;
}
}
getIndexToIns([10, 20, 30, 40, 50], 35);
getIndexToIns([10, 20, 30, 40, 50], 30);
getIndexToIns([40, 60], 50);
getIndexToIns([3, 10, 5], 3);
getIndexToIns([5, 3, 20, 3], 5);
getIndexToIns([2, 20, 10], 19);
getIndexToIns([2, 5, 10], 15);```