Permutations in JavaScript?

前端 未结 30 3400
不思量自难忘°
不思量自难忘° 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:14

    var inputArray = [1, 2, 3];
    
    var result = inputArray.reduce(function permute(res, item, key, arr) {
        return res.concat(arr.length > 1 && arr.slice(0, key).concat(arr.slice(key + 1)).reduce(permute, []).map(function(perm) { return [item].concat(perm); }) || item);
    }, []);
    
    
    alert(JSON.stringify(result));
    

提交回复
热议问题