An anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once,
These are the examples
car = arc arc = car brag = grab
bored = robed cat = act cider = cried
In the first example we have eat = tea
, here tea can be formed by eat by rearranging,
So now the task is not to find anagram but grouping them together from a list of elements.
for example, if we are given this array which contains anagram
["dusty", "night",'tea', "robed","ate","study","thing","eat"]
Then after grouping it should be something like below
[
['dusty', 'study'],
['night', 'thing'],
['tea', 'ate', 'eat'],
['robed']
]
So the idea is very simple,We keep an object and we sort each element and add as a key and value will be same as incoming element(without sorting),so if the sorted element is already present as key then we just push the element to existing array of elements
So the object looks like below,
[]
here is the code for the same
<script>
function groupAnagrams(array) {
let reducedObject = array.reduce((acc, cur) => {
let newcur=cur.split('').sort().join('');
if (!acc[newcur]) {
acc[newcur] = [cur]
} else {
acc[newcur] = [...acc[newcur], cur]
}
return acc;
}, {});
return Object.values(reducedObject);
}
console.log(groupAnagrams(["dusty", "night",'tea', "robed","ate","study","thing","eat"]));
</script>
Top comments (0)