Shuffling String Based on an Array in JavaScript



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
Updated on: 2021-01-19T06:08:33+05:30

299 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements
close