1

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

2
  • What sort of output would you want instead? An object can't have multiple identical keys, so having two Washington keys wouldn't be possible Commented Apr 13, 2020 at 8:01
  • I will be fine with something like this "{Washington,Florida: [{..},{..}], Washington,Alabama: [{..},{..}], ...} . I will still need to parse each key later on to drop the State string, but at least I won't get stuck Commented Apr 13, 2020 at 8:07

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.