Grouping words with their anagrams in JavaScript


Anagrams:

Two words or phrases which can be made by arranging the letters of each other in a different order are called anagrams of each other, like rat and tar.

We are required to write a JavaScript function that takes in an array of strings that might contain some anagram strings. The function should group all the anagrams into separate subarrays and return the new array thus formed.

For example −

If the input array is −

const arr = ['rat', 'jar', 'tar', 'raj','ram', 'arm', 'mar', 'art'];

Then the output array should be −

const output = [
   ['rat', 'tar', 'art'],
   ['jar', 'raj'],
   ['ram', 'arm', 'mar']
];

Example

Following is the code −

const arr = ['rat', 'jar', 'tar', 'raj','ram', 'arm', 'mar', 'art'];
const groupSimilarWords = (arr = []) => {
   if (arr.length === 0){
      return arr;
   };
   const map = new Map();
   for(let str of arr){
      let sorted = [...str];
      sorted.sort();
      sorted = sorted.join('');
      if(map.has(sorted)){
         map.get(sorted).push(str);
      }else{
         map.set(sorted, [str])
      };
   };
   return [...map.values()];
};
console.log(groupSimilarWords(arr));

Output

Following is the console output −

[ [ 'rat', 'tar', 'art' ], [ 'jar', 'raj' ], [ 'ram', 'arm', 'mar' ] ]

Updated on: 27-Jan-2021

720 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements