如何构建一个不包含重复字符n个单独字符列表的字符串?在JavaScript中

假设我们n个单独的字符数组。我们需要编写一个包含所有这些数组的JavaScript函数。

该函数应构建所有可能的字符串,使-

  • 每个数组仅包含一个字母

  • 不得包含任何重复字符(因为数组可能包含公共元素)

出于这个问题的目的,我们将考虑这三个数组,但是我们将编写函数以使其在可变数量的数组下都能很好地工作-

const arr1 = [a,b ,c,d ];
const arr2 = [e,f ,g ,a];
const arr3 = [m, n, o, g, k];

示例

为此的代码将是-

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));

输出结果

控制台中的输出将是-

[
   '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'
]