7__Where my anagrams at.js 1.2 KB

1234567891011121314151617181920212223242526272829303132333435
  1. //
  2. // What is an anagram ? Well, two words are anagrams of each other if they both contain the same letters.For example:
  3. // 'abba' & 'baab' == true
  4. // 'abba' & 'bbaa' == true
  5. // 'abba' & 'abbba' == false
  6. // 'abba' & 'abca' == false
  7. // Write a function that will find all the anagrams of a word from a list. You will be given two inputs a word and an array with words. You should return an array of all the anagrams or an empty array if there are none. For example:
  8. // anagrams('abba', ['aabb', 'abcd', 'bbaa', 'dada']) => ['aabb', 'bbaa']
  9. // anagrams('racer', ['crazer', 'carer', 'racar', 'caers', 'racer']) => ['carer', 'racer']
  10. // anagrams('laser', ['lazing', 'lazy', 'lacer']) => []
  11. function anagrams(word, words) {
  12. wArr = word.split("").sort((a, b) => (a < b ? -1 : 1));
  13. let result = [];
  14. word = word.split("").sort((a, b) => a.localeCompare(b)).join("")
  15. for (let w of words) {
  16. if (word == w.split("").sort((a, b) => a.localeCompare(b)).join(""))
  17. result.push(w);
  18. }
  19. return result;
  20. }
  21. anagrams("abba", ["aabb", "abcd", "bbaa", "dada"]);
  22. //=> ['aabb', 'bbaa']
  23. anagrams("racer", ["crazer", "carer", "racar", "caers", "racer"]);
  24. //=> ['carer', 'racer']
  25. anagrams("laser", ["lazing", "lazy", "lacer"]);
  26. //=> []