Shifting string letters based on an array in JavaScript

JavascriptWeb DevelopmentFront End Technology

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 −

 Live Demo

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
raja
Published on 27-Feb-2021 05:50:17
Advertisements