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, '')))
Gutelaunetyp
  • 2,144
  • 4
  • 15
  • 40

2 Answers2

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);
Keith
  • 22,005
  • 2
  • 27
  • 44
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?

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320