Skip to content

Instantly share code, notes, and snippets.

@nuragic
Created August 5, 2020 15:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nuragic/7dba35dfae565509c6f9b9ece5d980f2 to your computer and use it in GitHub Desktop.
Save nuragic/7dba35dfae565509c6f9b9ece5d980f2 to your computer and use it in GitHub Desktop.
Remove repeated parts from a string (e.g. address)
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