Javascript map method on array of string elements

后端 未结 8 578
悲哀的现实
悲哀的现实 2021-01-11 10:09

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 a

8条回答
  •  刺人心
    刺人心 (楼主)
    2021-01-11 11:09

    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']
    

提交回复
热议问题