user3142695 user3142695 - 1 month ago 11
Javascript Question

Replace strings in an array

I need to replace strings in an array. Right now I'm using a

forEach
-loop and a
switch
, which doesn't feel very elegant:

let result = [];
source.forEach(el => {
switch (el) {
case 'replace':
result.push('with this'); break;
case ...:
...;
default:
result.push(el);
}
});
return result.join(',');


What I want to get is a replacement of the elements with another string or using the original string if there is no match.

The source array has 50 elements, the replacement array has 30 elements.

Answer

In cases where you desire a one-in-one-out manipulation of an array, the .map function is preferred:

return source.map(el => el === 'replace' ? 'with this' : el).join(',');

EDIT I see you've updated the question and you actually have 30 different strings that you wish to replace. In this case you should use a Map that is pre-populated with the "before" and "after" strings:

let replaceFunc = (function() {

    let replace = new Map([
        ['replace', 'with this']
    ]);

    return source => source.map(el => replace.has(el) ? replace.get(el) : el).join(',');
 })();

The IIFE is used to ensure one-time initialisation of the Map, and the returned function that is closed over the Map is assigned to replaceFunc.

> replaceFunc(['replace']);
"with this"
Comments