Home > Software engineering >  Filter an array from anagrams
Filter an array from anagrams

Time:08-10

I have an array of strings, and should remove all anagrams from it

I've got this function

I don't know why one word from anagrams is remaining.

function aclean(arr) {
  let map = new Map();

  for (let word of arr) {
    // split the word by letters, sort them and join back
    let sorted = word.toLowerCase().split('').sort().join(''); // (*)
    map.set(sorted, word);
  }
  return Array.from(map.values());
}


let arr = ["nap", "teachers", "pna", "anp"];

console.log(aclean(arr))
// ["anp", "teachers"]

CodePudding user response:

Map keys are unique, so calling .set() on a map will either add a key if it's new or update a key if it's not. Because your sorting function turns "nap", "pna" and "anp" into the same thing ("anp") your loop is adding it, then updating it twice.

CodePudding user response:

Alex explained the problem, but to point you in the direction of a solution: try looping through the array and checking each word against the other words to see if it is an anagram of any of the others. If not, you can add it to the array that you will return.

Bonus: think of more efficient ways to do this. Can you make the list shorter as you go through? Can you do it in just one loop?

P.S. Did not give exact answer because figuring the details yourself will help you learn. Would normally post this as a comment, but I do not have enough rep here.

  • Related