Last active
July 24, 2018 09:33
-
-
Save christianwish/0a66d10d096e73a685c8a22df99bedc2 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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