简体   繁体   中英

Javascript: Creating a Dictionary/Map/Object with Sets as keys

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.

One way to do what you want is to convert a set to a string; for example,

 let map = new Map() let setSet = new Set([3, 1, 2]) let setKey = Array.from(setSet).sort().join() map.set(setKey, "foo") let getSet = new Set([2, 1, 1, 3]) let getKey = Array.from(getSet).sort().join() console.log(map.get(getKey)) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM