javascriptstringpalindrome

JS How to for palindrome


The question I have been given is this;

create a function that takes an array of words and returns an array containing only the palindromes.

A palindrome is a word that is spelled the same way backwards.

  E.g. ['foo', 'racecar', 'pineapple', 'porcupine', 'pineenip'] => ['racecar', 'pineenip']

This is the code that I create;

let arr = []
let str = words.slice(0)
let pal = str.toString().split("").reverse().join("") 
console.log(pal);


for (let i = 0; i < words.length; i++) {
for (let k = 0; k < pal.length; k++) {
 if (words[i] == pal[k]) {
   arr.push(words[i])
 }
 }
 }
 return arr
 }

This is the test that my code is run against;

describe("findPalindromes", () => {
it("returns [] when passed []", () => {
expect(findPalindromes([])).to.eql([]);
});
it("identifies a palindrom", () => {
 expect(findPalindromes(["racecar"])).to.eql(["racecar"]);
 });
it("ignores non-palindromes", () => {
expect(findPalindromes(["pineapple", "racecar", "pony"])).to.eql([
  "racecar"
]);
 });
 it("returns [] when passed no palindromes", () => {
expect(findPalindromes(["pineapple", "watermelon",      "pony"])).to.eql([]);
 });
});

Does anyone have any any suggestion of how to make my code work?


Solution

  • This is the simplest function that returns true or false if the str is a palindrome or not. I would use this in combination with the filter function to filter on all palindromes. Like this

    function checkPalindrom(str) { //function that checks if palindrome or not
        return str == str.split('').reverse().join('');
    }
    
    const result = words.filter(word => checkPalindrom(word)); //filter function that filters array to only keep palindromes