Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JS How to for palindrome [duplicate]

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?

like image 229
Geo Avatar asked Dec 16 '25 19:12

Geo


2 Answers

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
like image 70
Adam Lagevik Avatar answered Dec 19 '25 08:12

Adam Lagevik


What you have is good, however when you did

var pal = str.toString().split("").reverse().join("")

You changed from an array to a string, then you went into the loop with the string, so pal[k] gave a character and not a word.

To change pal back to an array of strings, split it again, use

var pal = str.toString().split("").reverse().join("").split(",");

var words = ['foo', 'racecar', 'pineapple', 'porcupine', 'pineenip'];

var arr = [];
var str = words.slice(0);
var pal = str.toString().split("").reverse().join("").split(",");
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])
    }
  }
}


console.log(arr);
like image 30
Stedman Dennis Avatar answered Dec 19 '25 07:12

Stedman Dennis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!