Let's say I have an array of permutations.
var D = [["A","B","C"],["A","C","B"],["B","A","C"],["B","C","A"],["C","A","B"],["C","B","A"]]
I want to do the opposite of listing all permutations of a combination. I want to find the unique combination of the permutations using javascript.
That unique combination would be
unique = [["A","B","C"]]
This is just a simple example. I want to find the unique combinations of a larger set of permutations with more elements, but I believe the solution would be scalable.
How do I find the unique combination using javascript?
This may be a solution:
var D = [["A","B","C"],["A","C","B"],["B","A","C"],["B","C","A"],["C","A","B"],["C","B","A"]];
const unique = [...new Map(D.map(i => [i.sort().join(''), i])).values()];
console.log(unique);
I'm a little unclear what you're asking, but I think it's that you want to find each symbol that occurs in the original list? Will every array within the original list contain the same characters (ie. all sub-arrays in var D will only be made up of "A", "B", and "C")?
If so, you could loop through your D array and keep track of each element you see in a Set, which will automatically de-dupe your output for you:
var D = [["A","B","C"],["A","C","B"],["B","A","C"],["B","C","A"],["C","A","B"],["C","B","A"]]
const uniques = new Set()
for(const arr of D) {
for(const c of arr) {
uniques.add(c)
}
}
console.log(uniques) // -> Set(3) {'A', 'B', 'C'}
Then, if that specific output format is needed, you can convert the set with something like
const arr = []
for(const c of uniques) {
arr.push(c)
}
const result = [ arr ]
console.log(result) // -> [['A', 'B', 'C']]