Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript map method on array of string elements

I am trying to understand how to implement the map method (rather than using a for loop) to check a string for palindromes and return boolean values for whether the mapped array elements reversed are the same as the original array elements. I cannot seem to understand the syntax of the map method. How do I get the map to function on each element in the original array? What is the value? Here is my working code, which is only logging a value of undefined:

function palindromeChecker(string) {
    var myString = string.toLowerCase();
    var myArray = myString.split(" ");
    var newArray = myArray.map(function (item) {
        item.split("").reverse().join("");
        return newArray === myArray;
    });
}

console.log(palindromeChecker("What pop did dad Drink today"));

Here is a link to the fiddle: https://jsfiddle.net/minditorrey/3s6uqxrh/1/

There is one related question here:

Javascript array map method callback parameters

but it doesn't answer my confusion about the syntax of the map method when using it to perform a function on an array of strings.

like image 691
Mindi Torrey Avatar asked Jan 21 '16 13:01

Mindi Torrey


People also ask

Can we use map function on string in Javascript?

Let's Map() Over a String()Turn the target string into an array, map() over it as per usual, and turn it back into a string: String. prototype. map = function(func) { let stringArray = this.

Can we use map function with string?

Remember that the map function will return a map object. Thus, we can use the string method join, which takes in an iterable (which the map object is, since it is an iterator, and all iterators are iterable), and then joins it into a string.

How do I map an array in Javascript?

The syntax for the map() method is as follows: arr. map(function(element, index, array){ }, this); The callback function() is called on each array element, and the map() method always passes the current element , the index of the current element, and the whole array object to it.


4 Answers

The map method will literally 'map' a function call onto each element in the array, take this as a simple example of increasing the value of each integer in an array by 1:

var items = [1,2,3];
items.map(function(item) { 
  return item + 1;
});

// returns [2,3,4]

In your case, you are trying to use map to accept or reject a string if it's a palindrome, so a simple implementation might be:

var items = ['mum', 'dad', 'brother'];
items.map(function(item) {
  return item.split('').reverse().join('') === item;
});

// returns [true, true, false]

I'm not 100% sure of your reasons for using map, because if you were trying to just filter the array and remove the strings that aren't palindromes, you should probably use the filter method instead, which works in the same way, but would remove any that return false:

var items = ['mum', 'dad', 'brother'];
items.filter(function(item) {
  return item.split('').reverse().join('') === item;
});

// returns ['mum', dad']

In your case you are splitting a string first to get your array of characters; you may also want to make that string lower case and remove punctuation, so an implementation might be:

var string = 'I live at home with my Mum, my Dad and my Brother!';
var items = string.toLowerCase().replace(/[^a-z0-9-\s]+/, '').split(' ');
items.filter(function(item) {
  return item.split('').reverse().join('') === item;
});

// returns ['i', 'mum', dad']

As mentioned in one of the comments on your question, you need to ensure you return a value from your function if you are using a separate function to perform the check, so this is how your function should look:

function checkPalindromes(string) {
  var items = string.toLowerCase().replace(/[^a-z0-9-\s]+/, '').split(' ');
  items.filter(function(item) {
    return item.split('').reverse().join('') === item;
  });

  return items;
}

And you would call it using:

checkPalindromes('I live at home with my Mum, my Dad and my Brother!'); // ['i', 'mum', 'dad']
like image 72
toomanyredirects Avatar answered Oct 19 '22 14:10

toomanyredirects


try something like this:

let str = 'hello';
let tab = [...str];

tab.map((x)=> {
    console.log("|"+x+"|");
    return x;
})
like image 37
marqn Avatar answered Oct 19 '22 13:10

marqn


newArray should include reversed version of theall items in myArray. After that, newArray should be reversed and joined with space in order to get the reversed version of the input string.

Here is the code:

function palindromeChecker(string) {
  var myString = string.toLowerCase();
  var myArray = myString.split(" ");
  var newArray = myArray.map(function (item) {
        return item.split("").reverse().join("");
    });
  console.log(newArray);
  return newArray.reverse().join(" ") === string;
}

console.log(palindromeChecker("dad did what"));
like image 24
Cem Ekici Avatar answered Oct 19 '22 13:10

Cem Ekici


Javascript map method on array of string elements by using split() function.

let str = 'hello';
      
    str.split('').map((x)=> {
        console.log("|"+x+"|");
        return x;
    })
like image 38
MOHAMMAD SIKANDAR Avatar answered Oct 19 '22 13:10

MOHAMMAD SIKANDAR