Search code examples
javascriptangulartypescriptecmascript-6ecmascript-2016

find and replace the value if exists in array using typescript map not working


I have an array which have set of values without space so I want find the value and replace it with space For ex:

dateOfJoining --> Date Of Joining

employmentStatus --> EmploymentStatus

let attributes =["dateOfJoining", "employmentStatus"]

let filtered = attributes.filter((item) => {
  if (item === 'dateOfJoining') {
    item = 'Date Of Joining';
  }

  if (item === 'employmentStatus') {
    item = 'Employment Status';
  }

  return item;
});

its always returning filtered =["dateOfJoining", "employmentStatus"] but its needs to return like ["Date Of Joining", "Employment Status"].

I have tried with above approach but its not returning the value as expected. IS their anyway to solve this?


Solution

  • You can use the forEach approach better for this use case.
    See example below:

    let attributes =["dateOfJoining", "employmentStatus"]
    
     attributes.forEach((item, index) => {
      if (item === 'dateOfJoining') {
        attributes[index] = 'Date Of Joining';
      }
    
      if (item === 'employmentStatus') {
        attributes[index] = 'Employment Status';
      }
      console.log('-*-*', item);
    });
    

    And even better without using any if else and unlimited number of sentences:

    let attributes =["dateOfJoining", "employmentStatus", "someOtherText", "andAnotherText"]
    
    attributes.forEach((item, index) => {
      var result = item.replace( /([A-Z])/g, " $1" );
        attributes[index] = result.charAt(0).toUpperCase() + result.slice(1);
    });
    
    console.log(attributes);   
    // ["Date Of Joining", "Employment Status", "Some Other Text", "And Another Text"]