
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Finding Final Direction of Movement in JavaScript
Problem
We are required to write a JavaScript function that takes in an array of single characters, arr, as the first and the only argument.
The array can contain of only 4 characters, they are −
- ‘N’ → stands for North direction
- ‘S’ → stands for South direction
- ‘W’ → stands for West direction
- ‘E’ → stands for East direction
Each character specifies a move of unit distance in that particular direction. And if anywhere in the array, two opposite directions, [(‘S’ and ‘N’) or (‘E’ and ‘W’)] appear adjacently, they cancel out the movement of each other. Therefore, our function is supposed to find the resulting direction of movement of the whole array.
For example, if the input to the function is −
const arr = ['N', 'S', 'S', 'E', 'W', 'N', 'W'];
Then the output should be −
const output = 'W';
Output Explanation
‘N’ and ‘S’ will cancel each other ‘E’ and ‘W’ will cancel each other and then finally ‘N’ and ‘S’ again cancels each other to leave behind only ‘W’.
Example
Following is the code −
const arr = ['N', 'S', 'S', 'E', 'W', 'N', 'W']; const cancelDirections = (arr = []) => { let str = arr.join(''); while(str.includes('NS') || str.includes('SN') || str.includes('EW') || str.includes('WE')){ str = str.replace('NS', ''); str = str.replace('SN', ''); str = str.replace('EW', ''); str = str.replace('WE', ''); }; return str.split(''); }; console.log(cancelDirections(arr));
Output
Following is the console output −
['W']