Skip to content

Instantly share code, notes, and snippets.

@nateflink
Created March 18, 2015 00:32
Show Gist options
  • Save nateflink/9f49dbe3f2efb7b6b51d to your computer and use it in GitHub Desktop.
Save nateflink/9f49dbe3f2efb7b6b51d to your computer and use it in GitHub Desktop.
JS function to determine if two strings are anagrams
function check_anagrams(first_words, second_words) {
if (first_words.length != second_words.length) {
console.log(0);
return;
}
var letters=[], is_anagram, first_word, second_word, exists;
for (var i=0; i<first_words.length; i++) {
first_word = first_words[i].split("");
second_word = second_words[i].split("");
if (first_words[i].length < 1 || second_words[i].length < 1) {
console.log(1);
continue;
}
letters = first_word.concat(second_word);
letters = letters.sort();
is_anagram = 1
if (letters.length %2 !== 0) {
is_anagram = 0
}
for (var j=0; j<letters.length-2; j+=2) {
//console.log(letters[j]+" "+letters[j+1])
if (letters[j]!=letters[j+1]) {
is_anagram = 0
}
}
//console.log(letters+" "+is_anagram);
// second check
exists = []
for (var f=0; f<first_word.length; f++) {
exists[f]="no";
for (var s=0; s<second_word.length; s++) {
if (second_word[s] == first_word[f]) {
exists[f]="yes";
break;
}
};
}
//console.log(exists)
if (exists.join("").indexOf("no") != -1) {
console.log(0);
continue;
}
//final
console.log(is_anagram);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment