user3142695 user3142695 - 1 year ago 86
Javascript Question

Replace strings in an array

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

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

let result = [];
source.forEach(el => {
switch (el) {
case 'replace':
result.push('with this'); break;
case ...:
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 Source

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

return => 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 => => 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"
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download