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
  • 233,700
  • 52
  • 457
  • 497
  • 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
  • 31,869
  • 13
  • 80
  • 91
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
  • 376,160
  • 25
  • 347
  • 392
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
  • 6,249
  • 10
  • 67
  • 125
RAJA K
  • 1