Is there any sensible way to make a dictionary in Javascript where the keys are Set objects?
For context, my problem is that I have a list of lists and want to count the number of times each combination occurs, ignoring the order and repetition of elements. I can make a dictionary where the lists themselves are elements, but if I try the same with a set, it treats every set as the same key with value: [object Set].
As an example:
var list_of_lists = [[1,2], [1], [1], [2,1], [1,1]]
var count_of_id_combos = {}
var count_of_id_combo_sets = {}
list_of_lists.forEach(
function(sub_list, index){
count_of_id_combos[sub_list] = (count_of_id_combos[sub_list] || 0) + 1
var set_of_sublist = new Set(sub_list)
count_of_id_combo_sets[set_of_sublist] = (count_of_id_combo_sets[set_of_sublist] || 0) + 1
}
)
console.log(count_of_id_combos) // -> Object {1: 2, 1,2: 1, 2,1: 1, 1,1: 1}
console.log(count_of_id_combo_sets) // -> Object {[object Set]: 5}
whereas I'd like the second object to be something like
Object {1: 3, 1,2: 2}
I've tried using Map as well and the same thing happens. The only solution I've come up with is manually filtering out duplicates and then sorting the lists, which works but seems overly complicated and I wondered if there was something I was missing.
Mapthat has instances ofSetas keys. But this won't work becausenew Set([1]) === new Set([1]); //falseeach new set will give a new key even though the content is the same.Map(0) {[object Set]: 5}as the output.Setreturns[object Set](e.g. try"" + new Set()to trigger it). Yury Tarabanko is talking about maps, which do not have that restriction on keys, so the set would not be stringified.const map = new Map([[new Set([1]), 1], [new Set([1]), 2]])try loggingmap