Reputation: 1075
I have working code for a simple word flipper:
var strFlip = function(str) {
return str.split(" ").map(function(word) {
return word.split("").reverse().join("");
}).join(" ");
};
console.log(strFlip("This is designed to swap the letter order of each word in the string"));
// "sihT si dengised ot paws eht rettel redro fo hcae drow ni eht gnirts"
I want to add an if/else to allow this code to now identify if each word in a string is a palindrome (spelled the same forward and backward ex: hannah).
So I tried continuing the .map() logic with:
var strFlip = function(str) {
return str.split(" ").map(function(word) {
return word.split("").reverse().join("");
}).join(" ").toLowerCase().map(function(test) {
if (test.split(" ") === word){
return true;
}else{
return false;
}
}
);
};
console.log(strFlip("Hannah loves her racecar"));
BUT.... unsurprisingly, it returns an error essentially stating that the long linked collection of functions before the if
section is not itself a function:
TypeError: str.split(...).map(...).join(...).toLowerCase(...).map is not a function
I was also getting lost trying to match all of the curly braces, but I think I got them all.
So, is it possible to add the if/else within?
Upvotes: 1
Views: 662
Reputation: 4651
.join(" ").toLowerCase()
returns a string, not an array. The error is stating that 'some string'.map
is not a function because it's undefined
.
If what you want is an array that indicates whether a word at an index is a palindrome then...
var sentence = 'Eve drives a racecar',
words = sentence.split(" ").map(function(word) {
var isPalindrome = word.length > 1 && (word.toLowerCase() === word.toLowerCase().split("").reverse().join(""));
return { text: word, isPalindrome: isPalindrome };
});
alert(JSON.stringify(words));
Upvotes: 2