Day 5: For . . . Of
-
-
MikeLDJ 9 years ago This can't be solved... not for the begginers.
-
wzaccone64 9 years ago compare each character at the beginning of the string against each character at the end of the string, and move the beginning and ending indexes as long as it is still a paladrum or until the indices meet each other.
for(var str of my_array){ var ldx = str.length - 1; var pala = true; var idx = 0; while ((pala) && (idx < str.length) && (idx != ldx)) if (str[idx++] != str[ldx--]) pala = false; if (pala) console.log(str); }
-
givonz 9 years ago imho, this is far more intuitive, than using the reverse function. personally, i built a reverse of the string with a concat from the end. then compare the two strings.
-
-
-
MistaTwist 9 years ago //Would something like this work?
"use strict"
function isPalindrome(str) { return str === str.split('').reverse().join(''); }
var palindromes = my_array.filter(isPalindrome);
for(let pal of palindromes){ console.log(pal); }
-
[deleted] 9 years ago Great @MistaTwist, nicely done!! :)
We can make our code more crisp, using arrow functions.
"use strict" for(let palindrome of my_array.filter(str => str === str.split('').reverse().join(''))) console.log(palindrome)
-
MistaTwist 9 years ago Ah yes, of course ;) Thanks!
-
MistaTwist 9 years ago One question though - what's the ideal use of arrow functions, with regards to reuse of functions?
Let's say I wanted to use isPalindrome elsewhere - could I just call isPalindrome(str) in the arrow function like this:
//assume my function is defined ok
for(let palindrome of my_array.filter(str => isPalindrome(str)){ console.log(palindrome); }
Thanks :)
-
[deleted] 9 years ago Yes!, you can create a separate arrow function and call it.
Something like this will work:"use strict" let isPalindrome = str => str === str.split('').reverse().join('') for(let palindrome of my_array.filter(item => isPalindrome(item))) console.log(palindrome)
And yes! creating a separate isPalindrome() function will make the code more readable+reusuable and hence it is recommended to do so :).
-
MistaTwist 9 years ago Great, thanks for confirming! I think I'm starting to get to grips more with ES6 syntax :D
-
-
-
jonmcclung 9 years ago This is what I did (except the "use strict", I don't know what that means) and this contest is the first experience I have with Javascript!
-
omi_tewary92 9 years ago but it is not taking care of constraint given size of each string lies between 0 and 100
-
[deleted] 9 years ago Those constraints are for the testcases. it is to inform the user about test case constraints.
-
-
-
-
JChiquin 7 years ago One-liner solution:
console.log(my_array.filter(a=>a==a.split('').reverse().join('')).join('\n'));
-
BONUS CHALLENGE
Gratz! If you have solved this challenge.
But
Can you try solving this using
filter
andfor ... of
?Add Reply Preview cancel