I’m trying to solve this challenge ‘Where do I belong’ but I realized that all four solutions provided in the guide involved untaught methods. Is there any simpler or maybe longer solutions that involved only the covered methods?
**Your browser information:**
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/93.0.4577.82 Safari/537.36 Edg/93.0.961.52
I’m not using i but here I’m trying to run the loop for "arr.length" times and for now I couldn’t recall any method to do that other than for loop (maybe while loop does the same thing?).
I’ll probably use .indexOf(), but for now I couldn’t proceed because I’m getting the right output for newArr.
The problem might lies within the loop count because when I replace arr.length + 1 with 3 I got the expected output which is [40, 50, 60]. But idk what’s the exact mistake I made.
function getIndexToIns(arr, num) {
arr.push(num)
let i = 0;
let newArr = [];
while (i < arr.length + 1){
let max = Math.max(...arr);
newArr.unshift(max);
arr.splice(arr.indexOf(max), 1);
i++;
}
return newArr;
}
console.log(getIndexToIns([40, 60], 50));
I seemed to be replying to myself haha but I finally got it WOOHOO!
Here’s my ingenious solution:
function getIndexToIns(arr, num) {
let arrr = [...arr]
arrr.push(num)
let i = 0;
let newArr = [];
while (i < arr.length + 1){
let max = Math.max(...arrr);
newArr.unshift(max);
arrr.splice(arrr.indexOf(max), 1);
i++;
}
return newArr.indexOf(num);
}
getIndexToIns([40, 60], 50);