0

I have the following:

 var arr = [{id: 0, title: 'This is a test Hello World Hello'}, {id: 1, title: 'I like the World'}, {id: 2, title: 'The Sun is bright'}, {id: 3, title: 'Cat'}],
replaceMents = ['Hello', 'World'];

I would like to have the array like that after the replacement:

[{
  id: 0,
  title: 'This is a test'
}, {
  id: 1,
  title: 'I like the'
}, {
  id: 2,
  title: 'The Sun is bright'
}, {
  id: 3,
  title: 'Cat'
}]

As I don't want to use a classical arr.forEach, I'm searching for a nicer solution.

Which possibilities are there ?

I thought something like

var newArr = arr.map(el => replaceMents.forEach(rep => el.title.replace(rep, '')))

1
  • 1
    You don't assign replace's return value anywhere, so it's lost. Commented Apr 5, 2019 at 22:00

2 Answers 2

3

Another option without using regex, and then maybe needing another regex to escape special characters. Is you could split filter join.

const arr = [{id: 0, title: 'This is a test Hello World Hello'}, {id: 1, title: 'I like the World'}, {id: 2, title: 'The Sun is bright'}, {id: 3, title: 'Cat'}]
const replaceMents = ['Hello', 'World'];

const newArr = arr.map(({ id, title }) => (
  { id, title: 
    title.split(' ').
      filter(f => !replaceMents.includes(f)).
      join(' ')
  }));
console.log(newArr);

Sign up to request clarification or add additional context in comments.

Comments

2

One option would be to construct a regular expression that alternates between every word to replace, then inside .map, replace all instances of those words with the empty string:

const arr = [{id: 0, title: 'This is a test Hello World Hello'}, {id: 1, title: 'I like the World'}, {id: 2, title: 'The Sun is bright'}, {id: 3, title: 'Cat'}]
const replaceMents = ['Hello', 'World'];

const pattern = new RegExp(replaceMents.join('|'), 'g');

const newArr = arr.map(({ id, title }) => ({ id, title: title.replace(pattern, '').trim() }));
console.log(newArr);

If the replacements may contain characters with a special meaning in a regular expression (like ., $, etc), then you need to escape them before joining:

const escapeRegex = s => s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');

new RegExp(replaceMents.map(escapeRegex).join('|'), 'g')

Is there a RegExp.escape function in Javascript?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.