简体   繁体   中英

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. 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. That will probably solve the problem but will require me to mutate my dataset or write another lookup function for State codes.

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)?

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"]))

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