Created
August 5, 2020 15:52
-
-
Save nuragic/7dba35dfae565509c6f9b9ece5d980f2 to your computer and use it in GitHub Desktop.
Remove repeated parts from a string (e.g. address)
This file contains hidden or 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
function uniqueStringReducer(str, options) { | |
const { splitChar = '', joinChar = ', ', locale = Intl.DateTimeFormat().resolvedOptions().locale } = options || {}; | |
const strParts = str.split(', ').map(s => s.trim()); | |
const uniqueAddressParts = strParts.reduce((accumulatedParts, currentPart, i) => { | |
const hasDuplicates = accumulatedParts.find(accPart => { | |
const isDifferent = (currentPart.localeCompare(accPart, locale, { sensitivity: 'base' })); | |
return !isDifferent; | |
}); | |
if (!hasDuplicates) { | |
accumulatedParts.push(currentPart); | |
} | |
return accumulatedParts; | |
}, []); | |
return uniqueAddressParts.join(joinChar); | |
} | |
console.log(uniqueStringReducer('Victor Larco Herrera , Perú , Víctor larco Herrera, La Libertad, 13009, Peru')); | |
// "Victor Larco Herrera, Perú, La Libertad, 13009" | |
console.log(uniqueStringReducer('Puerta del Sol, Puerta del SOL, Comunidad de Madrid, 28001, Madrid, MADRID')); | |
// "Puerta del Sol, Comunidad de Madrid, 28001, Madrid" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment