Codewars: middle element

Challenge

My code so far

function gimme (triplet) {
return triplet.indexOf(triplet.sort((a, b) => a-b)[1])
}

When I submit my code I get the message

for [1,2,3], expected 0 but got 1: expected 1 to equal 0

Isn’t 2 clearly the middle element in this test case, and the index of 2 being 1? Why do they expect 0 for this test case?

I know this seems incredibly trivial and my mistake is glaring at me but this test case failure is extremely frustrating rn. 2 is clearly the “middle element” in size and its index in the input array is 1, no?

You are sorting the array which mutate it ,then checking the position of the middle value.

edit: oh about your question. it expects “0” because the middle value isn’t the middle element in some cases.

if you check the sample test you will see unsorted array with middle value which is “2” in the start of that array

	doTest([2, 3, 1], 0)

the issue can be fixed by your style ,if you create new sorted array, get the middle value of it, then check the position of the middle value in the old array.

2 Likes

Understood. Completely forgot about mutations, thanks a ton.

1 Like

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