JavaScript group anagram performance I created an algorithm to create lists of anagrams
The input is [&quot;eat&quot;, &quot;tea&quot;, &quot;tan&quot;, &quot;ate&quot;, &quot;nat&quot;, &quot;bat&quot;]
Then, the output should be:
[[&quot;eat&quot;,&quot;tea&quot;,&quot;ate&quot;],[&quot;tan&quot;,&quot;nat&quot;],[&quot;bat&quot;]]
Each array is words that are anagram.
My solution is:
function group(input) {
    let result = [];
    if(input.length === 0){
        return result;
    }

    for(let i=0; i&lt;input.length; i++){
        let check = true;
        for(let j=0; j&lt;result.length; j++){
            if(result[j].includes(input[i])){
                check = false;
            }
        }
        if(check){
            result.push(checkAnagrams(input, i)); 
        }
    }

    return result;
}

function checkAnagrams(aStr, i){
    let anagrams = [];
    anagrams.push(aStr[i]);
    for(let j=0; j&lt;aStr.length; j++){
        if(i !== j){
            if(isAnagram(aStr[i], aStr[j])){
                anagrams.push(aStr[j]);
            }
        }
    }
    return anagrams;
}

function isAnagram(str1, str2) {
    // split =&gt; string into array
    // sort =&gt; sort the array
    // join =&gt; string to array
    // trim =&gt; remove any space
    const string1 = str1.split(&quot;&quot;).sort().join().trim();
    const string2 = str2.split(&quot;&quot;).sort().join().trim();
    if(string1 === string2){
        return true;
    } 
    return false; 
}

I know it works, but I was wondering if there is a better way to implement it.
Thanks
Welcome to Code Review, the complexity of your code can be reduced using a Map object having as keys sorted lexicographically strings and as values arrays of their anagrams. For example you will have the following couples key - value starting from your input:
key = &quot;aet&quot;  value = [&quot;eat&quot;,&quot;tea&quot;,&quot;ate&quot;]
key = &quot;ant&quot;  value = [&quot;tan&quot;,&quot;nat&quot;]
key = &quot;abt&quot;  value = [&quot;bat&quot;]

So you can define a function anagrams like this:
function anagrams(input) {
    const map = new Map();

    for (let i = 0; i &lt; input.length; ++i) {
        const key = [...input[i]].sort().join('');
        const value = map.has(key) ? map.get(key) : [];
        value.push(input[i]);
        map.set(key, value);
    }

    return [...map.values()];
}

/*below it will print the expected result*/
console.log(anagrams([&quot;eat&quot;, &quot;tea&quot;, &quot;tan&quot;, &quot;ate&quot;, &quot;nat&quot;, &quot;bat&quot;])); 

I just used the Spread operator to expand the string input[i] to array of characters and after I sort it to obtain the corrisponding key in the map. After I add it to the array of strings associated to the key and finally I return the map values as an array.
Note: I'm a javascript beginner so every hint or criticism about my answer is highly appreciated.