Lets Say I have a list like
Dog dOg God doggy dogg Zebra Wood
What I want to do is find all the words in the list regardless of case, or regardless of the actual word. I want to match the letters and take a count. So fr开发者_C百科om above
Dog, dOg, God would all be a match and in this case would return "3" as the count, but doggy, dogg, zebra, wood.. would all be unique and all would return 1 as the count.. Though I know this is possible I don't know where to begin. The anagram concept throws me off a bit. Any ideas?
var words = new Array("Dog", "dOg", "God", "doggy", "dogg","Zebra", "Wood");
var unique = {};
// iterate over all the words
for (i=0; i < words.length; i++) {
// get the word, all lowercase
var word = words[i].toLowerCase();
// sort the word's letters
word = word.split('').sort().join('')
// keep a count of unique combinations
if(unique[word])
unique[word] += 1;
else
unique[word] = 1;
}
// print the histogram
for (u in unique)
document.write(u + ": " + unique[u] + "<br/>")
here's what I came up with... jsfiddle here
$(document).ready(function() {
var mywords = ['Dog', 'dOg', 'God', 'doggy', 'dogg', 'Zebra', 'Wood'];
var finalArr = {};
for (var i = 0; i < mywords.length; i++) {
var temp = mywords[i].toLowerCase();
var letters = temp.split('');
var sorted = letters.sort();
var final = sorted.join("");
if(typeof finalArr[final] != 'undefined'){
finalArr[final] ++;
} else {
finalArr[final] = 1;
}
}
console.log(finalArr);
for(var i in finalArr) {
alert(i + ': ' + finalArr[i]);
document.write(i + ': ' + finalArr[i] + "<br/>");
}
});
精彩评论