Search code examples
javascriptfor-looppalindrome

Palindromes in Javascript


My goal is to take each word and compare it to the reverse. The code moves nicely until the forEach() loop. Trying word === word.reverse() doesn't work, but hopefully you get the idea. I want to compare the word to the reversed version to find the Palindromes. I realize there are ways to do this only using filter, but the goal is to do it with forEach(). Any suggestions to a simple fix to this is appreciated. Thanks!

//************************* Finding  Palindromes******************/

let arr = "I love Mom she, she is radar mom?"

function pallindromes(arr){
if(arr.length == 0) return console.log(null)the Pa

arr = arr.toLowerCase()
arr = arr.replace(/[?,]/g,"")
arr = arr.split(" ")
arr = [...new Set(arr)]
let newList = []

arr.forEach(word=>{
    if(word === word.reverse()){
        newList.push(word)
    }
})
return console.log(newList)
}

pallindromes(arr)

Solution

  • changed : word.split("").reverse().join("")

    let arr = "I love Mom she, she is radar mom?"
    
    function pallindromes(arr) {
      if (arr.length == 0) return console.log(null);
    
      arr = arr.toLowerCase()
      arr = arr.replace(/[?,]/g, "")
      arr = arr.split(" ")
      arr = [...new Set(arr)]
      let newList = []
    
      arr.forEach(word => {
        if (word === word.split("").reverse().join("")) {
          newList.push(word)
        }
      })
      return console.log(newList)
    }
    
    pallindromes(arr)