2021年4月23日星期五

Get All Variations from number of options

I have this array:

options = ['A', 'B', 'C']  

I want to extract all variations from those options with all possible directions as string separated by comma and space , it should looks like:

Variations = ['A', 'B', 'C', 'A, B', 'A, C', 'A, B, C','A, C, B', 'B, A', 'B, C', 'B, A, C', 'B, C, A', 'C, A', 'C, B', 'C, B, A', 'C, A, B']  

In my experiments I used the following method to get almost what I want, but not exact

options = ['A', 'B', 'C']    const powerSet = arr => {    return arr.reduce(      (total, value) =>        total.concat(          total.map(totalItem => [value].concat(totalItem).join(', '))        ),      [[]]    )  }    const rightLeftArray = powerSet(options)  const leftRightArray = powerSet(options.reverse())    const mergedArrays = rightLeftArray.concat(leftRightArray)    const filteredArray = mergedArrays.filter(el => el.length !== 0)  const uniqArray = [...new Set(filteredArray)]    console.log('uniqArray', uniqArray)    // I Got this result:  uniqArray = ["A", "B", "B, A", "C", "C, A", "C, B", "C, B, A", "B, C", "A, C", "A, B", "A, B, C"]  

I appreciate if you could get more accurate results with minimum code.

https://stackoverflow.com/questions/67203966/get-all-variations-from-number-of-options April 22, 2021 at 05:54AM

没有评论:

发表评论