0

my aim is to test for a palindrome (word is the same forwards and backwards) and the log and array containing only the palindromes, so far this is the most I could come with.


const getAllPalindromes = (words) => {
 return words.filter((word) => {
  word.split("").reverse().join("") === word;
  });
};

console.log(getAllPalindromes(["hello", "noon"]));

To my understanding this should return an array containing the items that are true from the boolean, any pointers will help a newbie thanks a lot!

ej001
  • 9
  • 1
  • 4
  • 1
    Welcome to SO! You need `return` inside the filter otherwise everything in the array is treated as falsey since `undefined` is the default return value of any function in JS. Or use the implicit return value of unbracketed arrow funcs that point to a single expression. – ggorlen Jun 02 '20 at 22:14
  • 1
    Ace! got it working thanks – ej001 Jun 02 '20 at 22:22

1 Answers1

0

You're not returning your filter conditional. You do the comparison, but then don't return it so the filter has an undefined as the return of the comparator, and thus it doesn't filter anything. Otherwise, the rest of your logic is correct!

const getAllPalindromes = (words) => words.filter((word) => word.split("").reverse().join("") === word);

console.log(getAllPalindromes(["hello", "noon"]));

Since you're using Arrow Functions we're going to use the implicit return in them to make things a little smaller especially since each function is really just a single statement. Here's the same code in a longer format for direct comparison

const getAllPalindromes = function (words) {
 return words.filter(function (word) {
    return word.split("").reverse().join("") === word;
  });
};

console.log(getAllPalindromes(["hello", "noon"]));

The differences between Arrow Functions and Functions was already answered a long time ago, so here it is for reference.

It might also help if you use an editor or code linter that can help you catch the problems early. A missed return statement is just as easy to make as an off by one error.

Off by One errors are as easy to make as a missed return statement undefined

Happy coding!

Robert Mennell
  • 1,954
  • 11
  • 24