

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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' ] ]
- Related Questions & Answers
- Arranging words by their length in a sentence in JavaScript
- Reversing the words within keeping their order the same JavaScript
- Checking for string anagrams JavaScript
- Program to find the largest grouping of anagrams from a word list in Python
- Are the strings anagrams in JavaScript
- Complicated array grouping JavaScript
- Explain Grouping operator in JavaScript.
- Grouping array values in JavaScript
- Grouping nested array in JavaScript
- Map anagrams to one another in JavaScript
- C# program to determine if Two Words Are Anagrams of Each Other
- Grouping data to monthwise in JavaScript
- Grouping identical entries into subarrays - JavaScript
- Group Anagrams in Python
- Select and sum with grouping in MySQL?
Advertisements