|
| 1 | +To find all anagrams, let's split every word to letters and sort them. When letter-sorted, all anagrams are same. |
| 2 | + |
| 3 | +For instance: |
| 4 | + |
| 5 | +``` |
| 6 | +nap, pan -> anp |
| 7 | +ear, era, are -> aer |
| 8 | +cheaters, hectares, teachers -> aceehrst |
| 9 | +... |
| 10 | +``` |
| 11 | + |
| 12 | +We'll use the letter-sorted variants as map keys to store only one value per each key: |
| 13 | + |
| 14 | +```js run |
| 15 | +function aclean(arr) { |
| 16 | + let map = new Map(); |
| 17 | + |
| 18 | + for (let word of arr) { |
| 19 | + // split the word by letters, sort them and join back |
| 20 | +*!* |
| 21 | + let sorted = word.toLowerCase().split('').sort().join(''); // (*) |
| 22 | +*/!* |
| 23 | + map.set(sorted, word); |
| 24 | + } |
| 25 | + |
| 26 | + return Array.from(map.values()); |
| 27 | +} |
| 28 | + |
| 29 | +let arr = ["nap", "teachers", "cheaters", "PAN", "ear", "era", "hectares"]; |
| 30 | + |
| 31 | +alert( aclean(arr) ); |
| 32 | +``` |
| 33 | + |
| 34 | +Letter-sorting is done by the chain of calls in the line `(*)`. |
| 35 | + |
| 36 | +For convenience let's split it into multiple lines: |
| 37 | + |
| 38 | +```js |
| 39 | +let sorted = arr[i] // PAN |
| 40 | + .toLowerCase() // pan |
| 41 | + .split('') // ['p','a','n'] |
| 42 | + .sort() // ['a','n','p'] |
| 43 | + .join(''); // anp |
| 44 | +``` |
| 45 | + |
| 46 | +Two different words `'PAN'` and `'nap'` receive the same letter-sorted form `'anp'`. |
| 47 | + |
| 48 | +The next line put the word into the map: |
| 49 | + |
| 50 | +```js |
| 51 | +map.set(sorted, word); |
| 52 | +``` |
| 53 | + |
| 54 | +If we ever meet a word the same letter-sorted form again, then it would overwrite the previous value with the same key in the map. So we'll always have at maximum one word per letter-form. |
| 55 | + |
| 56 | +At the end `Array.from(map.values())` takes an iterable over map values (we don't need keys in the result) and returns an array of them. |
| 57 | + |
| 58 | +Here we could also use a plain object instead of the `Map`, because keys are strings. |
| 59 | + |
| 60 | +That's how the solution can look: |
| 61 | + |
| 62 | +```js run demo |
| 63 | +function aclean(arr) { |
| 64 | + let obj = {}; |
| 65 | + |
| 66 | + for (let i = 0; i < arr.length; i++) { |
| 67 | + let sorted = arr[i].toLowerCase().split("").sort().join(""); |
| 68 | + obj[sorted] = arr[i]; |
| 69 | + } |
| 70 | + |
| 71 | + return Object.values(obj); |
| 72 | +} |
| 73 | + |
| 74 | +let arr = ["nap", "teachers", "cheaters", "PAN", "ear", "era", "hectares"]; |
| 75 | + |
| 76 | +alert( aclean(arr) ); |
| 77 | +``` |
0 commit comments