How to check anagrams in JavaScript?

by roel_stanton , in category: JavaScript , a year ago

How to check anagrams in JavaScript?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

by maryam_feest , a year ago

@roel_stanton 

To check if two strings are anagrams in JavaScript, you can follow these steps:

  1. Convert both strings to lowercase to ensure that the comparison is case-insensitive.
  2. Remove any non-alphabetic characters from the strings (such as spaces or punctuation).
  3. Convert each string to an array of characters using the split() method.
  4. Sort the character arrays alphabetically using the sort() method.
  5. Join the sorted character arrays back into strings using the join() method.
  6. Compare the two sorted and joined strings. If they are equal, then the original strings are anagrams.


Here's an example implementation:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
function areAnagrams(str1, str2) {
  // Convert both strings to lowercase and remove non-alphabetic characters
  str1 = str1.toLowerCase().replace(/[^a-z]/g, '');
  str2 = str2.toLowerCase().replace(/[^a-z]/g, '');

  // Convert each string to an array of characters and sort alphabetically
  const sortedStr1 = str1.split('').sort().join('');
  const sortedStr2 = str2.split('').sort().join('');

  // Compare the sorted and joined strings
  return sortedStr1 === sortedStr2;
}

// Example usage:
console.log(areAnagrams('rail safety', 'fairy tales')); // true
console.log(areAnagrams('hello', 'world')); // false


This implementation assumes that the input strings contain only alphabetic characters and spaces or punctuation that should be ignored. If the input strings could contain non-ASCII characters or other special cases, you may need to modify the implementation to handle those cases appropriately.

by schuyler.moore , 20 days ago

@roel_stanton 

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
function areAnagrams(str1, str2) {
  // Function to clean and sort a string
  const cleanAndSort = str => str.toLowerCase().replace(/[^a-z]/g, '').split('').sort().join('');

  // Clean and sort both input strings
  const sortedStr1 = cleanAndSort(str1);
  const sortedStr2 = cleanAndSort(str2);

  // Compare the cleaned and sorted strings
  return sortedStr1 === sortedStr2;
}

// Example usage:
console.log(areAnagrams('rail safety', 'fairy tales')); // true
console.log(areAnagrams('hello', 'world')); // false


This code snippet refactors the implementation to preprocess the input strings through a cleanAndSort function. This function cleans and sorts the strings, which reduces code repetition and makes the main areAnagrams function cleaner and easier to read. This approach also enhances maintainability, as changes to the cleaning and sorting logic only need to be made in one place.