简体   繁体   English

Javascript:以集合为键创建字典/地图/对象

[英]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? 有什么明智的方法可以在Javascript中将键设置为Set对象的字典?

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] . 我可以制作一个字典,其中的列表本身就是元素,但是如果我尝试使用集合,则将每个集合都当作具有值的相同键: [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. 我也尝试过使用Map ,同样的事情也会发生。 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)) 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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