r/CodingHelp • • Jul 02 '21

[Javascript] Problem with JavaScript code

Post image
62 Upvotes

19 comments sorted by

View all comments

10

u/LeaveTheWolf Jul 02 '21

.splice() mutates the array. So your logic for removing the encountered element is only guaranteed to be correct on the first pass. After that it is pretty likely to fail. For what it is worth, I do think this might work for the very specific case of a valid array passed in descending order.

Anyway you need to change your .splice() call to use .indexOf() to find the array index instead of your attempt at indexing myArray[].

Let me know if you need more than that, but hopefully it helps.

6

u/Cheesybread4ever Jul 02 '21

Oh my goodness! I’ve been staring at this function for so long and completely missed how .splice messes up the index of everything in array. I actually just added ,0 at the end of the splice, so that when the number is removed it’s replaced with a 0.

4

u/LeaveTheWolf Jul 02 '21

That will work! Good quick fix.