- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
- Related Articles
- Shifting string letters based on an array in JavaScript
- Randomly shuffling an array of literals in JavaScript
- Modify an array based on another array JavaScript
- Filter an object based on an array JavaScript
- Forming and matching strings of an array based on a random string in JavaScript
- Encrypting a string based on an algorithm in JavaScript
- Encrypting a string based on an algorithm using JavaScript
- Splitting an array based on its first value - JavaScript
- Constructing a string based on character matrix and number array in JavaScript
- Sort array based on another array in JavaScript
- Filter array based on another array in JavaScript
- Sorting Array based on another array JavaScript
- Filter an array containing objects based on another array containing objects in JavaScript
- Order an array of words based on another array of words JavaScript
- Creating an array of objects based on another array of objects JavaScript

Advertisements