- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- 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
How to build a string with no repeating character n separate list of characters? in JavaScript
Suppose, we n separate array of single characters. We are required to write a JavaScript function that takes in all those arrays.
The function should build all such possible strings that −
contains exactly one letter from each array
must not contain any repeating character (as the arrays might contain common elements)
For the purpose of this problem, we will consider these three arrays, but we will write our function such that it works well with variable number of arrays −
const arr1 = [a,b ,c,d ]; const arr2 = [e,f ,g ,a]; const arr3 = [m, n, o, g, k];
Example
The code for this will be −
const arr1 = ['a','b' ,'c','d' ]; const arr2 = ['e','f' ,'g' ,'a']; const arr3 = ['m', 'n', 'o', 'g', 'k']; const allCombinations = (...arrs) => { let res = []; const reduced = arrs.reduce((acc, b) => acc.reduce((r, v) => { return r.concat(b.map(el => { return [].concat(v, el); })) }, []) ); res = reduced.filter(el => new Set(el).size === el.length); return res.map(el => el.join(' ')); }; console.log(allCombinations(arr1, arr2, arr3));
Output
And the output in the console will be −
[ 'a e m', 'a e n', 'a e o', 'a e g', 'a e k', 'a f m', 'a f n', 'a f o', 'a f g', 'a f k', 'a g m', 'a g n', 'a g o', 'a g k', 'b e m', 'b e n', 'b e o', 'b e g', 'b e k', 'b f m', 'b f n', 'b f o', 'b f g', 'b f k', 'b g m', 'b g n', 'b g o', 'b g k', 'b a m', 'b a n', 'b a o', 'b a g', 'b a k', 'c e m', 'c e n', 'c e o', 'c e g', 'c e k', 'c f m', 'c f n', 'c f o', 'c f g', 'c f k', 'c g m', 'c g n', 'c g o', 'c g k', 'c a m', 'c a n', 'c a o', 'c a g', 'c a k', 'd e m', 'd e n', 'd e o', 'd e g', 'd e k', 'd f m', 'd f n', 'd f o', 'd f g', 'd f k', 'd g m', 'd g n', 'd g o', 'd g k', 'd a m', 'd a n', 'd a o', 'd a g', 'd a k' ]
Advertisements