Javascript - Generating all combinations of elements in a single array (in pairs)

后端 未结 9 628
天命终不由人
天命终不由人 2020-11-28 11:14

I\'ve seen several similar questions about how to generate all possible combinations of elements in an array. But I\'m having a very hard time figuring out how to write an a

9条回答
  •  旧巷少年郎
    2020-11-28 11:54

    Just to give an option for next who'll search it

    const arr = ['a', 'b', 'c']
    const combinations = ([head, ...tail]) => tail.length > 0 ? [...tail.map(tailValue => [head, tailValue]), ...combinations(tail)] : []
    console.log(combinations(arr)) //[ [ 'a', 'b' ], [ 'a', 'c' ], [ 'b', 'c' ] ]

提交回复
热议问题