针对字谜数组测试单词 - Javascript

Test word against array for anagrams - Javascript

到目前为止..我有这个:

function anagrams(word, words) {
  for(let i = 0; i <= words.length; i++){
  const aCharMap = buildCharMap(word);
  const bCharMap = buildCharMap(words[i]);

  if(Object.keys(aCharMap).length !== Object.keys(bCharMap).length) {
    words.pop(words[i])
  }
  for (let char in aCharMap) {
    if (aCharMap[char] !== bCharMap[char]) {
    words.pop(words[i]);
    }
  }
  console.log(word);
  console.log(words);
  }
}

  function buildCharMap(str) {
  const charMap = {};
  for (let char of str.replace(/[^\w]/g, '').toLowerCase()) {
  charMap[char] = charMap[char] + 1 || 1;
  }
  return charMap;
}

如果您通读代码,手头的问题很明显,但这里是

编写一个函数,从列表中找出一个单词的所有变位词。您将获得两个输入,一个单词和一个包含单词的数组。您应该 return 一个包含所有字谜的数组,如果有 none,则应该是一个空数组。例如:

anagrams('abba', ['aabb', 'abcd', 'bbaa', 'dada']) => ['aabb', 'bbaa']

anagrams('racer', ['crazer', 'carer', 'racar', 'caers', 'racer']) => ['carer', 'racer']

anagrams('laser', ['lazing', 'lazy', 'lacer']) => []

pop是按照你的方式使用的吗?

或者你可以这样做:

function anagrams(word, words) {
let result = [];
const aCharMap = buildCharMap(word);

// you also had a off-by-one error in loop 
for (let i = 0; i < words.length; i++) {
    const bCharMap = buildCharMap(words[i]);

    let isAnagram = (a, b) => {
        if (Object.keys(a).length !== Object.keys(b).length) return false;
        for (let char in a) {
            if (aCharMap[char] !== b[char]) {
                return false
            }
        }
        return true;
    }

    if (isAnagram(aCharMap, bCharMap)) result.push(words[i])

}

function buildCharMap(str) {
    const charMap = {};
    for (let char of str.replace(/[^\w]/g, '').toLowerCase()) {
        charMap[char] = charMap[char] + 1 || 1;
    }
    return charMap;
}

return result
}

console.log(anagrams("test", ["estt", "ttee", "tset"]))