3

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?

Thelouras
  • 852
  • 1
  • 10
  • 30
Geo
  • 439
  • 2
  • 5
  • 15
  • 1
    I disagree with that, he's not asking how to do a Palindrome check. He's asking his particular solution isn't working. And as I stated in my answer, he just needs to split the variable pal to get it in the form of an array. – Stedman Dennis Dec 22 '18 at 12:17

6 Answers6

3

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
Adam Lagevik
  • 673
  • 1
  • 7
  • 15
  • This code doesn't pass the provided tests, though. – ksav Dec 22 '18 at 13:37
  • `return str.toLowerCase().split('').reverse().join('') === str.toLowerCase();` would make it work with words that have a mix of both upper & lower case letters. – Hamzeen Hameem Jun 27 '19 at 07:18
0
    function isPalindrome(word) {
        const firstHalf = word.slice(0, Math.ceil(word.length/2));
        const secondHalfReversed = word.slice(Math.floor(word.length/2)).split('').reverse().join('');

        return firstHalf === secondHalfReversed;
    }

    function getPalindromesFromArray(arr) {
        return arr.filter(isPalindrome);
    }

    const wordsArr = ['foo', 'racecar', 'pineapple', 'porcupine', 'pineenip'];

    console.log(getPalindromesFromArray(wordsArr));
lazuxd
  • 36
  • 3
  • Could you please elaborate on your code, https://stackoverflow.com/help/how-to-answer – SR_ Dec 22 '18 at 12:18
0

Without giving spoilers to the answer (this is a common interview question) a clean approach would be as follows:

  1. Define a function isPalindrome(string): boolean
  2. Use the filter property available on the Array prototype to return an array of only palindromes e.g. inputArray.filter(isPalindrome)

Both can be unit tested separately, for example:

You could define an array of inputs and expected outputs for isPalindrome [{ input: "racecar", expectedOutput: true}, {input: "pineapple", expectedOutput: false}, ...] and loop over each test case.

Kunal
  • 1,125
  • 2
  • 11
  • 18
0

using for loop and filter

let arr = ["foo", "racecar", "pineapple", "porcupine", "pineenip",'pap','aaaa'];
let palindromes = arr.filter(w => {
  let len = w.length;
  for (let i = 0; i < len / 2; i++) {
    if (w[i] == w[len - i - 1]) {
      return true;
    } else {
      return false;
    }
  }
});
console.log(palindromes)
Elish
  • 486
  • 3
  • 12
0

To solve that first I would create an isPalindrome function like this:

function isPalindrome(word) {
  palindromeWord = ''
  for(var i = word.length - 1; i >= 0; i--) {
    palindromeWord += word.charAt(i)
  }

  return palindromeWord === word
}

and then I would check for each word inside the array like this:

let arr =  ['foo', 'racecar', 'pineapple', 'porcupine', 'pineenip']

let palindromeArr = []

arr.forEach(word => {
  if (isPalindrome(word)) {
    palindromeArr.push(word)
  }
})

console.log(palindromeArr)
af costa
  • 296
  • 4
  • 13
0

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);