get all combinations for a string

前端 未结 8 1687
傲寒
傲寒 2020-12-01 19:34

I\'m trying to create a function in JavaScript that given a string will return an array of all possible combinations of the letters with each used at most once, starting wit

8条回答
  •  -上瘾入骨i
    2020-12-01 20:08

    You could use a nasty trick and increase a counter and use its binary representation as flags:

     function combine(str){
       const result = [];
       for(let i = 1; i < Math.pow(2, str.length) - 1; i++)
          result.push([...str].filter((_, pos) => (i >> pos) & 1).join(""));
      return result;
    }
    

    Try it

提交回复
热议问题