[英]How To Group Objects In Array By Unique Properties in Javascript?
So My problem is that I am trying to group my array of contacts by "County", My only problem is that my grouping function works... not really.所以我的问题是我试图按“县”对我的联系人数组进行分组,我唯一的问题是我的分组 function 有效……不是真的。 If you run my code, you'll see that it groups as expected;如果你运行我的代码,你会看到它按预期分组; My only issue is that Washington, Florida and Washington, Alabama are two different counties that shouldn't be grouped together.我唯一的问题是,佛罗里达州的华盛顿州和阿拉巴马州的华盛顿州是两个不同的县,不应归为一类。 I know I can try to append an additional piece of info to the county in order to make it unique, like so: Washington,FL & Washington,AL.我知道我可以尝试向 append 提供该县的附加信息,以使其独一无二,例如:Washington,FL & Washington,AL。 That will probably solve the problem but will require me to mutate my dataset or write another lookup function for State codes.这可能会解决问题,但需要我改变我的数据集或为 State 代码编写另一个查找 function。
So is there a way that I can simply make sure that my function groups by unique county based on each data it has in hand on each object (like the State)?那么有没有一种方法可以简单地确保我的 function 根据每个 object (如州)上的每个数据按唯一县分组?
Thanks for your help.谢谢你的帮助。
function groupBy(array, key) { return array.reduce((r, a) => {;(r[a[String(key)]] = r[a[String(key)]] || []).push(a) return r }, {}) } const contacts = [ { County: 'Washington', State: 'Florida', Country: 'United States', Name: 'Bob Michael', }, { County: 'Washington', State: 'Alabama', Country: 'United States', Name: 'John Doe', }, ] console.log(groupBy(contacts, "County"))
You could take a group of keys and join the values to a single key.您可以获取一组键并将值连接到单个键。
function groupBy(array, keys) { return array.reduce((r, o) => { const key = keys.map(k => o[k]).join('|'); (r[key] = r[key] || []).push(o); return r; }, {}); } const contacts = [ { County: 'Washington', State: 'Florida', Country: 'United States', Name: 'Bob Michael', }, { County: 'Washington', State: 'Alabama', Country: 'United States', Name: 'John Doe', }, ] console.log(groupBy(contacts, ["Country", "State", "County"]))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.