Created
August 6, 2021 15:51
-
-
Save kwaiks/dd3824fd0d3ff6a28d46b0fcf46c7470 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function groupAnnagrams(arr) { | |
const arrObject = {} // create an empty object to store each words | |
for(let i=0; i <arr.length; i++){ | |
arrObject[arr[i]] = {} // create empty object so it wont be undefined | |
for(let j = 0; j < arr[i].length; j++){ | |
const key = arrObject[arr[i]][arr[i][j]]; | |
if(!key){ //check falsy value | |
arrObject[arr[i]][arr[i][j]] = 1; // set 1 if not exist | |
}else{ | |
arrObject[arr[i]][arr[i][j]] += 1; //increment if exist | |
} | |
} | |
} | |
let doneArr = []; // store all words that have been checked | |
let result = []; | |
for(let i = 0; i < arr.length; i++){ | |
let groups = [arr[i]] | |
if(doneArr.includes(arr[i])) continue; // skip loop if string already checked | |
for(let j = i+1; j < arr.length; j++){ | |
let count = 0; | |
for(key in arrObject[arr[i]]){ | |
if(arrObject[arr[i]][key] === arrObject[arr[j]][key]){ | |
count++; | |
} | |
} | |
if(count === Object.keys(arrObject[arr[i]]).length){ // check if all words are same | |
groups.push(arr[j]); | |
doneArr.push(arr[j]); | |
} | |
} | |
result.push(groups) | |
} | |
} | |
const input = ['kita','atik','tika','aku','kia','makan','kua']; | |
console.log(groupAnnagrams(input)); // [["kita", "atik", "tika"], ["aku", "kua"], ["kia"], ["makan"]] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment