Skip to content

Instantly share code, notes, and snippets.

@saadshahd
Last active November 17, 2016 22:56
Show Gist options
  • Save saadshahd/864bb3462a5aa045dfe6c7a3466d44d6 to your computer and use it in GitHub Desktop.
Save saadshahd/864bb3462a5aa045dfe6c7a3466d44d6 to your computer and use it in GitHub Desktop.
function getSameCharStrings(strings) {
const repeatedCharsOrSpaceRegex = /(\w)(?=.*\1)|\s/g;
const uniqueSortedChars = strings.map(word => {
return word
.replace(repeatedCharsOrSpaceRegex, '')
.split('')
.sort()
.join('');
});
const indexes = uniqueSortedChars.reduce((currentIndexes, chars, index) => {
currentIndexes[chars] = currentIndexes[chars] || [];
currentIndexes[chars].push(index);
return currentIndexes;
}, {});
return Object.keys(indexes)
.filter(key => indexes[key].length >= 2)
.map(key => {
return indexes[key].map(index => strings[index]);
});
}
// getSameCharStrings(['alllo', 'ooooiiio', 'be ee', 'alo', 'loa', 'be', 'io', 'sad'])
/* Results
* [
* ['alllo', 'alo', 'loa'],
* ['ooooiiio', 'io'],
* ['be ee', 'be']
* ];
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment