0

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?

3
  • 1
    Is .filter the right tool here? Looks like you are trying to transform you array items for which the .map method would be better suited. Try using .map instead and I think your code may work as-is. Commented Jan 13, 2021 at 15:49
  • 1
    Use Array#map instead Commented Jan 13, 2021 at 15:50
  • Filter just tells whether an item should be kept or not Commented Jan 13, 2021 at 15:50

1 Answer 1

2

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"]
Sign up to request clarification or add additional context in comments.

3 Comments

@BlockHasher did you try this ?
hey Nadhir, it worked as expected, thanks a ton!
@BlockHasher great, can you please mark it as it correct answer

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.