
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
Shifting String Letters Based on an Array in JavaScript
Suppose we have a string that contains only lowercase english alphabets.For the purpose of this question, we define unit shifting of a letter as replacing that very letter to its succeeding letter in alphabets (including wrapping which means next to 'z' is 'a');
We are required to write a JavaScript function that takes in a string str as the first argument and an array of numbers arr of the same length that of str as the second argument. Our function should prepare a new string in which the letters of the original string are shifted by the corresponding units present in the array arr.
For example −
If the input string and the array are −
const str = 'dab'; const arr = [1, 4, 6];
Then the output should be −
const output = 'eeh';
Example
The code for this will be −
const str = 'dab'; const arr = [1, 4, 6]; const shiftString = (str = '', arr = []) => { const legend = '-abcdefghijklmnopqrstuvwxyz'; let res = ''; for(let i = 0; i < arr.length; i++){ const el = str[i]; const shift = arr[i]; const index = legend.indexOf(el); let newIndex = index + shift; newIndex = newIndex <= 26 ? newIndex : newIndex % 26; res += legend[newIndex]; }; return res; }; console.log(shiftString(str, arr));
Output
And the output in the console will be −
eeh
Advertisements