-2

How would you get all possible combinations of an array of numerical values similar to python itertools without using itertools npm package in this same order?

This is a python implementation.

from itertools import combinations

input = [0,1,2,3]

output = sum([list(map(list, combinations(input, i))) for i in range(len(input) + 1)], [])
>>> output
[[],
 [0],
 [1],
 [2],
 [3],
 [0, 1],
 [0, 2],
 [0, 3],
 [1, 2],
 [1, 3],
 [2, 3],
 [0, 1, 2],
 [0, 1, 3],
 [0, 2, 3],
 [1, 2, 3],
 [0, 1, 2, 3]]
6
  • 2
    Does this answer your question? How to find all subsets of a set in JavaScript? Commented May 5, 2020 at 14:52
  • That question returns subset of combinations, but does not address the order parameter. It does not answer this question. When running a test using the prescribed solution it returns unordered list of combinations. Commented May 5, 2020 at 15:15
  • The top comment on the accepted answer there reads: If you reverse [value,...set] to be [...set,value] then it also preserves order. If you take that answer and apply the patch described in the comment, then order is preserved and you will get exactly the output you gave in your example. Commented May 5, 2020 at 15:19
  • I integrated the top comment and the return does match the requested output. It only maintains order within each subset, but does not match the requriement. ``` const getAllSubsets = theArray => theArray.reduce((subsets, value) => subsets.concat(subsets.map(set => [...set,value])),[[]]); output [[] [0] [1] [0, 1] [2] [0, 2] [1, 2] [0, 1, 2] [3] [0, 3] [1, 3] [0, 1, 3] [2, 3] [0, 2, 3] [1, 2, 3] [0, 1, 2, 3]] ``` Commented May 5, 2020 at 15:27
  • 1
    Ah, I see yes the order is different, I apologize, my earlier comment was mistaken. You could certainly sort the result array after the fact: getAllSubsets([0, 1, 2, 3]).sort((a, b) => a.length - b.length || String(a).localeCompare(String(b))) Commented May 5, 2020 at 16:00

1 Answer 1

0

This function will return similar results as stated in the question and sorts the subsets and the complete array.

getAllSubsets function from How to find all subsets of a set in JavaScript?

function getUniqueSortedCombinations(inputArray){
  
  const getAllSubsets = theArray => theArray.reduce((subsets, value) => subsets.concat(subsets.map(set => [...set,value])),[[]]);
      
  let subset = getAllSubsets(inputArray)
      
  subset.sort((a, b) => a.length - b.length || String(a).localeCompare(String(b)))
      
  return subset
}

console.log(getUniqueSortedCombinations([0,1,2,3]))

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.