This is a stack:
var stack = [];
To check the top value of the stack (peek):
var top = stack[stack.length - 1]
push/pop the stack:
stack.pop()
stack.push(value)
Iterate over your array of directions. For each direction, rules are: peek at stack. If value on top of stack + current value in array are N/S or E/W, pop
stack. If they aren’t, push
the current value in the array to the stack.
This means there is only a single pass, and you don’t need to poke around or manipulate inside the array: the stack will end up having the correct directions in the correct order.