Skip to content

Instantly share code, notes, and snippets.

@jakepruitt
Last active December 20, 2015 07:09
Show Gist options
  • Select an option

  • Save jakepruitt/6090969 to your computer and use it in GitHub Desktop.

Select an option

Save jakepruitt/6090969 to your computer and use it in GitHub Desktop.
Code Challenge 7/26, count and sort a sample sentence.
var meSentence = "This is a test sentence and it is not the sentence we will ultimately test with";
// Create array
var meIndex = meSentence.replace(/[.,;'"]/, "").toLowerCase().split(" ");
// Instantiate object
var me = {};
// Tally wordcount
for (var i = 0; i < meIndex.length; i++) {
me[meIndex[i]] = 1;
for (var j = 0; j < i; j++) {
if (meIndex[i] == meIndex[j]) {
me[meIndex[i]]++;
};
};
};
// Eliminate duplicates in array
for (var i = 0; i < meIndex.length; i++) {
me[meIndex[i]] = 1;
for (var j = 0; j < i; j++) {
if (meIndex[i] == meIndex[j]) {
void meIndex.splice(j,1);
j--;
};
};
};
// Sort array
meIndex.sort(function compare(a, b) {
if (me[a] == me[b]) {
if (a > b) {
return 1;
} else{
return -1;
};
} else {
return me[b] - me[a];
};
});
// Formatted print
for (var i = 0; i < meIndex.length; i++) {
console.log(meIndex[i] + ": " + me[meIndex[i]])
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment