Skip to content

Instantly share code, notes, and snippets.

@Kernix13
Last active September 16, 2022 21:04
Show Gist options
  • Save Kernix13/8b9c16d88153f290b56150ca6a6e75fe to your computer and use it in GitHub Desktop.
Save Kernix13/8b9c16d88153f290b56150ca6a6e75fe to your computer and use it in GitHub Desktop.
JavaScript function to split, sort, and filter out repeats from a string
<p id="comma-output"></p>
<p id="space-output"></p>
// Function to sort words then strip out repeats
// Used to get unique keywords from different web languages/tools I've used to get ideas for blog posts. I tend to have a lot of repeats...
const commaSeparated = "split, sort, and, filter, strings, separated, by, commas, with, no, repeats, repeats, repeats";
const spaceSeparated = "split sort and filter strings separated by spaces with no repeats repeats repeats";
let commaWords = [];
let spaceWords = [];
function splitStrings(str, separator, output) {
return str
.toLowerCase()
.split(separator)
.sort((a, b) => a.localeCompare(b))
.filter(word => {
if (!output.includes(word)) {
output.push(word);
}
});
}
const commaCount = splitStrings(commaSeparated, ", ", commaWords);
document.getElementById("comma-output").innerHTML = commaWords.join(", ");
splitStrings(spaceSeparated, " ", spaceWords);
document.getElementById("space-output").innerHTML = spaceWords.join(", ");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment