Search code examples
javascriptarraysstringsubstr

Replace last letters in array of strings Javascript


I need to do as follows:

I've got an array of strings containing last names. Some of them ends with letter 'i'.

manLastNames = ["testowski","bucz","idzikowski","gosz"];

I need to make a function which will iterate over this array of strings and if there is an element ending with 'i', I need to replace this 'i' for 'a', otherwise just leave string as it is.

At the end I want to have another array where all last 'i's are replaced with 'a's.

womanLastNames = ["testowska","bucz","idzikowska","gosz"];

This is what I have now, but Im pretty sure that it start being crap at some point

    var rep = function() {
  var manLastNames = ["testowski","bucz","idzkowski","gosz"];
  var womanLastNames = new Array(4);


  for (var i=0; i<manLastNames.length; i++) {
    var lastName = manLastNames[i];
    if (lastName.substr(lastName.length - 1, 1) == 'i') {
        lastName = lastName.substr(0, lastName.length - 1) + 'a';
  }
  }

  for (var i=0; i<womanLastNames.length; i++) {
    womanLastNames[i] = lastName[i];

  }

  console.log(womanLastNames);
}
rep();

Solution

  • Here is solution

    var rep = function() {
      var manLastNames = ["testowski","bucz","idzkowski","gosz"];
      var womanLastNames =[];
    
      for (var i=0; i<manLastNames.length; i++) {
        var lastName = manLastNames[i];
        if (lastName.charAt(lastName.length - 1) == 'i') {
            lastName = lastName.substr(0, lastName.length - 1) + 'a';
       }
       womanLastNames.push(lastName);
      }
      console.log(womanLastNames);
    }
    rep();

    Another solution is to use .map method like this, using a callback function:

    var manLastNames = ["testowski","bucz","idzikowski","gosz"];
    function mapNames(item){
       return item[item.length-1]=='i' ? item.substr(0, item.length-1) + "a" : item;
    }
    console.log(manLastNames.map(mapNames));