Skip to content

Instantly share code, notes, and snippets.

@christianwish
Last active July 24, 2018 09:33
Show Gist options
  • Save christianwish/0a66d10d096e73a685c8a22df99bedc2 to your computer and use it in GitHub Desktop.
Save christianwish/0a66d10d096e73a685c8a22df99bedc2 to your computer and use it in GitHub Desktop.
const headToTail = (i, v) => (v.substring(i) + v.substring(0, i));
const createSharedId = str => str
.split('')
.reduce((acc, a) => ([...acc, headToTail(acc.length, str.toLowerCase())]), [])
.sort()[0];
const valueReducer = (acc, { src, sharedId }) => (typeof acc[sharedId] === 'undefined')
? { ...acc, [sharedId]: [src] }
: { ...acc, [sharedId]: [ ...acc[sharedId], src] };
const toGroupedObj = arr => arr
.map(v => ({ src: v, sharedId: createSharedId(v) }))
.reduce(valueReducer, {});
const groupValues = arr => Object.values(toGroupedObj(arr));
// Use:
const result = groupValues(["Tokyo", "London", "Rome", "Donlon", "Kyoto", "Paris"]);
console.log(result); // [ [ 'Tokyo', 'Kyoto' ],[ 'London', 'Donlon' ],[ 'Rome' ],[ 'Paris' ] ]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment