# JavaScript: Generate all permutations of a string

## JavaScript fundamental (ES6 Syntax): Exercise-136 with Solution

Write a JavaScript program to generate all permutations of a string (contains duplicates).

• Use recursion.
• For each letter in the given string, create all the partial permutations for the rest of its letters.
• Use Array.prototype.map() to combine the letter with each partial permutation.
• Use Array.prototype.reduce() to combine all permutations in one array.
• Base cases are for String.prototype.length equal to 2 or 1.
• WARNING: The execution time increases exponentially with each character. Anything more than 8 to 10 characters will cause your environment to hang as it tries to solve all the different combinations.

Sample Solution:

JavaScript Code:

``````//#Source https://bit.ly/2neWfJ2
const stringPermutations = str => {
if (str.length <= 2) return str.length === 2 ? [str, str[1] + str[0]] : [str];
return str
.split('')
.reduce(
(acc, letter, i) =>
acc.concat(stringPermutations(str.slice(0, i) + str.slice(i + 1)).map(val => letter + val)),
[]
);
};

console.log(stringPermutations('abc'));
console.log(stringPermutations('*\$*'));
```
```

Sample Output:

```["abc","acb","bac","bca","cab","cba"]
["*\$*","**\$","\$**","\$**","**\$","*\$*"]
```

Pictorial Presentation:

Flowchart:

Live Demo:

See the Pen javascript-basic-exercise-136-1 by w3resource (@w3resource) on CodePen.

Improve this sample solution and post your code through Disqus

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.

﻿

## JavaScript: Tips of the Day

Returns an array of n-tuples of consecutive elements

Example:

```const tips_arr = (n, arr) =>  n > arr.length ? [] : arr.slice(n - 1).map((v, i) =>[...arr.slice(i, i + n - 1), v]);
console.log(tips_arr(2, [1, 2, 3, 4, 5]));
console.log(tips_arr(3, [1, 2, 3, 4, 5]));
console.log(tips_arr(5, [1, 2, 3, 4]));
```

Output:

```[[1, 2], [2, 3], [3, 4], [4, 5]]
[[1, 2, 3], [2, 3, 4], [3, 4, 5]]
[]
```