Basic algorithm Scripting: Where do I belong I am stuck

I got stuck trying to find the last index of the array.

  1. When there are duplicate numbers in the array how do I get the last one and not the first one?

2)If I iterated through the entire array how do I get the last index and then return it + 1?

I cant really wrap my head around it…

Code so far:

function getIndexToIns(arr, num) {
// Find my place in this sorted array.
let sortedArr = arr.sort();

for(let i = 0; i < sortedArr.length; i++){
if(num < sortedArr[i] || num == sortedArr[i]){
return sortedArr.indexOf(sortedArr[i]);



getIndexToIns([40, 60], 50);

First of all, please use the “Ask for help” button to ask about a challenge. It formats your code and provides a link to the challenge so we don’t have to go looking for it.

You code … There are different ways to solve this, and this is certainly a perfectly cromulent one.

OK, you start out sorting the array - good start. But you’ve misunderstood something about the sort method. By default it sorts strings, so for numbers you need to provide a callback function to tell it to compare them differently. You can find the docs here. Let us know if you can’t figure it out. Callback functions are one of the weird/wonderful things about JS, but they certainly do take a while to get used to.

Next, this:

if(num < sortedArr[i] || num == sortedArr[i]){

works but could be simplified to:

if (num <= sortedArr[i]) {

Lastly, with all that in place. You just need to account for if the num is bigger than anything in the array. You need another return somewhere after the if loop. (You may have to make a slight adjustment to how your iteration variable - i - is declared. I say “may” because there is more than one way to handle it.)

When I make those changes, your code passes.