Shuffling string based on an array in JavaScript

JavascriptWeb DevelopmentFront End Technology

We are required to write a JavaScript function that takes in a string, say str as the first argument and an array of positive integers, say arr of the same length as the second argument.

Our function should shuffle the characters in the string such that the character at the ith position moves to arr[i] in the shuffled string.

For example −

If the input string and the array are −

const str = 'example';
const arr = [5, 2, 0, 6, 4, 1, 3];

Then the output should be −

const output = 'alxepem';

Example

Following is the code −

const str = 'example';
const arr = [5, 2, 0, 6, 4, 1, 3];
const shuffleString = (str = '', arr = []) => {
   let res = '';
   const map = new Map();
   for (let i = 0; i < arr.length; i++) {
      const char = str.charAt(i), index = arr[i]
      map.set(index, char)
   };
   for (let i = 0; i < arr.length; i++){
      res += map.get(i);
   };
   return res;
};
console.log(shuffleString(str, arr));

Output

Following is the console output −

alxepem
raja
Published on 19-Jan-2021 06:07:52
Advertisements