Skip to content

Instantly share code, notes, and snippets.

@gani88
Created June 12, 2024 09:49
Show Gist options
  • Save gani88/8296e9ff057060e7a6996e20589c6ede to your computer and use it in GitHub Desktop.
Save gani88/8296e9ff057060e7a6996e20589c6ede to your computer and use it in GitHub Desktop.
Anagram : Grouping words to two dimensional array based on anagram of word
function anagram(arr) {
const forAnagram = {};
// Creating function to place element/characters into specific index in some string
function insertElement(word, idx, element) {
let newString = '';
for (let i = 0; i < word.length; i++) {
if (i === idx) {
newString += element;
}
newString += word[i];
}
return newString
}
// Make function to sorted the characters or word from arr
function anagramSort(word) {
let sorted = '';
for (let i = 0; i < word.length; i++) {
let passed = false; // this is for flag, to check the word already in sorted var
let charToPlaced = word[i]; // add char to sorted var
// Looping for sorted var to find the correct position for the char
for (let j = 0; j < sorted.length; j++) {
// This condition is to check if the current char in word is less than the char in sorted
if (charToPlaced < sorted[j]) {
sorted = insertElement(sorted, j, charToPlaced); // Using above function to place the current char in sorted
passed = true; // flag change, indicate flag has been placed
break; // stop the looping
}
}
if (!passed) {
sorted += charToPlaced
}
}
return sorted;
}
// this is for grouping the word inside dictionary/object for anagram
for (const arrays of arr) {
const finalWord = anagramSort(arrays);
if (!forAnagram[finalWord]) {
forAnagram[finalWord] = [];
}
forAnagram[finalWord].push(arrays);
}
// And this is for extracting the anagram to be grouped in result array
const result = [];
for (const combine in forAnagram) {
result.push(forAnagram[combine]);
}
return result;
}
let words = ['cook', 'save', 'taste', 'aves', 'vase', 'state', 'map'];
console.log(anagram(words))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment