Complete the code to check if two strings have the same length.
function areAnagrams(str1, str2) {
if (str1.length [1] str2.length) {
return false;
}
return true;
}We return false if the lengths are not equal, so the operator should be !==.
Complete the code to sort the characters of a string.
function sortString(str) {
return str.split('').[1]().join('');
}reverse() only reverses the array, not sorts it.map() or filter() does not sort.To sort characters, we use the sort() method on the array.
Fix the error in the code to count character frequencies correctly.
function charFrequency(str) {
const freq = {};
for (const char of str) {
freq[char] = (freq[char] || [1]) + 1;
}
return freq;
}We start counting from zero if the character is not yet in the object.
Fill both blanks to create a function that checks if two strings are anagrams by sorting.
function areAnagrams(str1, str2) {
return str1.split('').[1]().join('') [2] str2.split('').sort().join('');
}We sort both strings and compare them with strict equality to check for anagrams.
Fill all three blanks to check if two strings are anagrams using character frequency counts.
function areAnagrams(str1, str2) {
if (str1.length !== str2.length) return false;
const freq1 = {};
const freq2 = {};
for (const char of str1) {
freq1[char] = (freq1[char] || [1]) + 1;
}
for (const char of str2) {
freq2[char] = (freq2[char] || [2]) + 1;
}
for (const char in freq1) {
if (freq1[char] [3] freq2[char]) {
return false;
}
}
return true;
}We start counts at zero, then check if frequencies are not equal using !==.
