Permutations in JavaScript?

前端 未结 30 2706
不思量自难忘°
不思量自难忘° 2020-11-21 06:52

I\'m trying to write a function that does the following:

  • takes an array of integers as an argument (e.g. [1,2,3,4])
  • creates an array of all the possib
30条回答
  •  旧巷少年郎
    2020-11-21 07:10

    Functional answer using flatMap:

    const getPermutationsFor = (arr, permutation = []) =>
      arr.length === 0
        ? [permutation]
        : arr.flatMap((item, i, arr) =>
            getPermutationsFor(
              arr.filter((_,j) => j !== i),
              [...permutation, item]
            )
          );
    

提交回复
热议问题