This challenge involves transforming an array of directions to ensure no backtracking occurs while retaining only the necessary instructions. Despite my initial confidence in solving the problem, the outcome was not as anticipated. Can anyone provide guidance on identifying errors in my code?
function dirReduc(arr){
let y = 0,
index = 0,
directions = [];
arr.forEach(function(movement){
if(movement == "NORTH"){
if(directions.includes("SOUTH")){
index = directions.indexOf("SOUTH")
directions.splice(index, 1)
} else{
directions.push("NORTH")
}
}
else if(movement == "SOUTH"){
if(directions.includes("NORTH")){
index = directions.indexOf("NORTH")
directions.splice(index, 1)
} else{
directions.push("SOUTH")
}
}
else if(movement == "EAST"){
if(directions.includes("WEST")){
index = directions.indexOf("WEST")
directions.splice(index, 1)
} else{
directions.push("EAST")
}
}
else if(movement == "WEST"){
if(directions.includes("EAST")){
index = directions.indexOf("EAST")
directions.splice(index, 1)
} else{
directions.push("WEST")
}
}
});
return directions
}