Last active
September 16, 2022 21:04
-
-
Save Kernix13/8b9c16d88153f290b56150ca6a6e75fe to your computer and use it in GitHub Desktop.
JavaScript function to split, sort, and filter out repeats from a string
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
<p id="comma-output"></p> | |
<p id="space-output"></p> |
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
// 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