Skip to content

Instantly share code, notes, and snippets.

@ryangoree
Last active March 28, 2022 18:01
Show Gist options
  • Save ryangoree/76fda064f59e8106f5ef115c7c841457 to your computer and use it in GitHub Desktop.
Save ryangoree/76fda064f59e8106f5ef115c7c841457 to your computer and use it in GitHub Desktop.
function groupStrings(strings) {
return Object.values(strings.sort().reduce((a, str) => {
const s = str.toLowerCase();
const f = s[0];
a[f] = a[f] ? [...a[f], s] : [s];
return a;
}, {}));
}
@ryangoree
Copy link
Author

groupStrings(['bear', 'chicken', 'dolphin', 'cat', 'tiger'])
// [
//   ['bear'],
//   ['cat', 'chicken'],
//   ['dolphin'],
//   ['tiger']
// ]

groupStrings(['chevrolet', 'buick', 'dodge', 'bmw', 'mercedes', 'jaguar', 'landrover', 'audi', 'volkswagen', 'cadilac', 'ford', 'toyota', 'tesla'])
// [
//   ['audi'],
//   ['bmw', 'buick'],
//   ['cadilac', 'chevrolet'],
//   ['dodge'],
//   ['ford'],
//   ['jaguar'],
//   ['landrover'],
//   ['mercedes'],
//   ['tesla', 'toyota'],
//   ['volkswagen'],
// ]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment