0

Instead of individually passing through the argument how can I loop through an array and check to see if each word is a palindrome? If it is I want to return the word if not i want to return a 0.

var myArray = ['viicc', 'cecarar', 'honda'];    

function palindromize(words) {
    var p = words.split("").reverse().join("");

    if(p === words){
        return(words);
    } else {
        return("0");
    }
}
palindromize("viicc");
palindromize("cecarar");
palindromize("honda");
thefourtheye
  • 221,210
  • 51
  • 432
  • 478
  • Look at a for-loop http://www.w3schools.com/js/js_loop_for.asp. – Dylan Meeus Jan 06 '16 at 16:02
  • 3
    Not trying to answer your question, but just a side-note. Your function does not try to make a given word a palindrome, so maybe calling it `isPalindrome` is better than `palindromize` even if you don't return a boolean value. – Stack0verflow Jan 06 '16 at 16:10
  • MDN just put up a pretty good JS tutorial; I suggest you run through it to get an idea about JS basics like loops. See https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript –  Jan 06 '16 at 16:16

3 Answers3

0

You'll want to use a for loop.

for (var i = 0; i < myArray.length; i++) {
    palindromize(myArray[i]);
}

I'd suggest you become intimately familiar with them as they are (arguably) the most common type of looping construct.

Mike Cluck
  • 30,526
  • 12
  • 76
  • 90
0

Just use Array.prototype.map():

The map() method creates a new array with the results of calling a provided function on every element in this array.

myArray.map(palindromize)

var myArray = ['viicc', 'cecarar', 'honda', 'ada'];

function palindromize(word) {
    var p = word.split("").reverse().join("");
    return p === word ? word : 0;
}

document.write('<pre>' + JSON.stringify(myArray.map(palindromize), 0, 4) + '</pre>');
Nina Scholz
  • 351,820
  • 24
  • 303
  • 358
0
var myArray = ['viicc', 'cecarar', 'honda', 'malayalam' ];   
var b = myArray.filter(function(c,d,f){
var Cur = c.split('').reverse().join('');
if(c == Cur){
console.log( myArray[d] +" " + " is Palindrome" );
}
});
Ghoul Fool
  • 5,346
  • 9
  • 63
  • 111
RAJA K
  • 1