All solutions provided were not covered in previous lessons

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`

Challenge: Where do I Belong

yes, it is solvable - what have you tried to solve it? where dis you get stuck?

Yes, it can be done with for loops, if statements, and simple addition.

1 Like

Also, the hint’s are a little misleading. You don’t need to sort the array to solve the problem.

1 Like

Here’s my solution but it couldn’t work idk where’s the problem

``````function getIndexToIns(arr, num) {
arr.push(num);
let newArr = [];
for (let i = 0; i < arr.length; i++){
newArr.unshift(Math.max(...arr))
arr.splice(arr.indexOf(Math.max(...arr)),1)
}
return newArr;
}

console.log(getIndexToIns([2,3,1], 1.5));      // returns [ 2, 3 ]
``````

first, `splice` is changing `arr` and that throws your loop out
but you are also not using `i` so you could do without the loop

what are the logical steps you are following to find the index?

try to use `console.log` to see what happening in there

2 Likes

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`.

Also can please further explain the following?

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);
``````

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.