0

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)
Johnny Bravo
  • 163
  • 11

3 Answers3

1

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)
Abhi
  • 995
  • 1
  • 8
  • 12
0

String does not have a reverse method, but array does.

So replace word.reverse() with word.split("").reverse().join("").

This will make an array, splitting the word on every letter, reverse it, and join it again.

0TTT0
  • 1,288
  • 1
  • 13
  • 23
0

What you want is actually a way to reverse a string in Javascript, because .reverse() is only usable for arrays. A lot of posts and questions cover that.

If I take this answer, I can reverse a string with s.split("").reverse().join("");, so by applying this to your code we get

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)

returning [ 'i', 'mom', 'radar' ]

I would still advise creating a reverseString() function, so that people not used to javascript can still easily read your code without having to guess what .split().reverse().join() does.

Cheers.

Ajuge
  • 18
  • 3