# Basic Algorithm Scripting - Where do I Belong

I did this without loop or if statement. That’s ok right?

``````function getIndexToIns(arr, num) {
arr.push(num);
arr.sort((a, b) => a - b);
let i = arr.length - 1;
let item = arr[i];
arr[i] = item;
return arr.indexOf(num);
}

console.log(getIndexToIns([5, 3, 20, 3], 5));
``````

User Agent is: `Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/105.0.0.0 Safari/537.36`

Challenge: Basic Algorithm Scripting - Where do I Belong

Ooff, that’s alot harder. I tried to do it like this before

``````function getIndexToIns(arr, num) {
arr.push(num);
let i = arr.length - 1;
let item = arr[i];
while (i > 0 && item < arr[i-1]) {
arr[i] = arr[i-1];
i -= 1;
}
arr[i] = item;
return arr.indexOf(num);
}

console.log(getIndexToIns([5, 3, 20, 3], 5));
``````

but it fails the console.log(getIndexToIns([5, 3, 20, 3], 5)); test all the time simply because it’s not sorting the number properly.
That sort a, b makes it so easy. xD

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