JavaScript Directions Reduction - I am struggling to locate the mistake in my code

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
}

Answer №1

Here is an innovative approach to tackle the task, simplifying conflicting movements and organizing them sequentially:

const steps=["north","north","west","south","west","north","east","north","west","south"];

const directionCount=steps.reduce((acc,current)=>(++acc[current],acc),
 {north:0,east:0,south:0,west:0});
let vertical=directionCount.north-directionCount.south,
  horizontal=directionCount.east-directionCount.west;
const result=(ns?Array(Math.abs(vertical)).fill(ns>0?"north":"south"):[])
   .concat(horizontal?Array(Math.abs(horizontal)).fill(horizontal>0?"east":"west"):[]);

console.log(result)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

I am experiencing an issue where my Laravel website does not refresh automatically

Having trouble with the URL (url: "/ultimo-pedidox"). It seems to be loading correctly, but the view isn't refreshing as expected. @extends('store/template') @section('content') <div style="margin-top: 55px;" ...

Instructions for incorporating animation into the CSS properties of an element as the class is updated using jQuery

The issue: I am facing a challenge with an HTML element that has a class called hidden which hides the element with the css attribute display: none;. When I use JavaScript to remove the class, the element immediately becomes visible again (the original di ...

Resolve feature for UI routes fails to function upon refreshing the page

My app utilizes UI Route for view routing. When accessing /berlinerliste/, a function is triggered to display an array of objects. If one of these objects is clicked, the view changes to /berlinerliste/{id}/ and shows the details of that specific object. ...

Error: The term 'function' is not recognized in this Javascript runtime

There seems to be an issue with my function being undefined, even though it is clearly defined below the content of the program. <button type="button" class="btn btn-primary" data-dismiss="modal" id="CmdBranchEditOk" onclick="CmdBranchEditOk_OnCli ...

Updating a JSON data structure after removing an item using AngularJS

As a newcomer to AngularJS, I have created a Service using Java and integrated it into Angular to handle the deletion of Contact objects. On my homepage in AngularJS, this is the code I have: <!--RESULTS--> <form> <table class="table table ...

Angular 2 - one service provider shared across various browser windows

I need to implement an alert system that notifies users when a task is completed, regardless of which page they are on at the time. The challenge is ensuring that the alert displays across all pages. To achieve this, I am utilizing a service that employs ...

What is the reason behind the shifting behavior of e.currentTarget when using event delegation in jQuery?

Click here for the code snippet <div id="container"> <button id="foo">Foo button</button> <button id="bar">Bar button</button> </div> $('#container').on('click', function(e) { var targ ...

Changing background color on scroll using jQuery

Looking to create a cool effect where the background color of a fixed header changes as the user scrolls down a full-page block website. Managed to get it mostly working in this Pen, but struggling with determining how much has been scrolled to trigger the ...

React is throwing an error message stating that setCount is not a valid function

Getting an error saying setCount is not a function. I am new to this, please help. import React, { memo, useState } from "react"; export const Container = memo(function Container() { const { count, setCount } = useState(0); return ( ...

Issue with dependency injection arises when module definition is used

As a beginner in Angular, I'd greatly appreciate it if you could point out any rookie mistakes I may be making here. Below is my module and controller structure: (function () { 'use strict'; angular .module('myApp&ap ...

Phantom is refusing to initialize/execute angularjs controller methods

I am seeking assistance in generating a PDF file from an HTML page that is controlled by an AngularJS controller. The PDF creation process involves using the Phantom module. My issue is that while data binding works correctly when I navigate to the specifi ...

Excessive event handler attachment causing IE8 memory degradation and performance deterioration

My website has nearly 3000 list elements, each with a click event handler and a hover event attached using jQuery. $('li').click(function (e){ // do processing here }) $('li').hover(function (e){ // do processing here for ho ...

Navigating through the elements of the DOM

Here is a function that deletes people from a list when you click on a certain part of the form: function ParticipantsDeleteClick(model, url) { for (i in model.Participants) { $("#delete" + i).click(function () { $.ajax({ url: url, ...

Create a list that starts with a header determined by an object's attribute within an array

Currently in Vue, I am attempting to create a list based on a specific property within an object. The array being retrieved from the vuex store is structured as follows: const array = [ { name: "British title string" nationality: "British" }, { ...

How can you pair a collection of foreign keys in one table with the primary key in another table?

I have two tables. The first one is structured like this: id | array_of_ids ---------------------- 001 | {012, 345, 789} 002 | {789, 123, 456} 003 | {234, 789, 567} 004 | {543, 210, 789} The second table looks like this: ids | str ------------- ...

The mysterious case of the perpetually false .Net Core Radio Button

I have a List that I want to send to the view and submit each item in the list through a form. Model: public partial class Model { public int Id { get; set; } public string UId { get; set; } public int WId { get; set; } ...

Is there a way to delete an Object from a MongoDB array without using $pull?

I'm in the process of developing a social media application, and I have created a route that allows users to like posts. However, I want the functionality such that if a user has already liked a post and clicks the "like" button again, it should remov ...

Tips for extracting nested data in Vue.js without redundancy

Here's a query regarding my "Avatar database" project. I am aiming to gather all tags from each avatar and compile them into a single array without any duplicates. For instance, if there are 3 avatars tagged as "red", the list in the array should onl ...

What is the process for transforming specific words within a sentence into clickable links?

In my experience with React, I faced the challenge of creating links within a string. After experimenting with various approaches, I finally discovered a solution without having to manipulate the DOM directly. function generateProfile() { const hashtagRe ...

Looking for a jQuery function to reload images?

I have a GIF image loading bar animation that I want to reload when the "Reload Image" button is clicked, so that the animation will repeat. //HTML <img src="http://i54.tinypic.com/2qdwtp0.gif" id="load-bar"/> <a href="#" id="reloadImg">Relo ...