Home > other >  How to replace 1 string with 2 strings in an array?
How to replace 1 string with 2 strings in an array?

Time:08-20

Here's an example:

I have this array:

const chars = [ "ä", "t", "i" ]

and I'd like to achieve this outcome:

const chars = ["a", "e", "t", "i" ]

Basically, I'd like to replace some special chars:

  • ä -> a, e
  • ü -> u, e
  • ö -> o, e

I've been trying to use a switch function like this:

    const charsArray = ["ä", "t", "i"]
    const replaceChars = (char) => {
          switch (char) {
            case "ä":
              return ("a", "e");
            default:
              return char;
          }
        };
    const cleanArray = charsArray.map((c) => {return replaceChars(c)}
    //output: ["e", "t", "i"] instead of: ["a","e", "t", "i"]

The problem: it only returns 1 value, so f.ex. for "ä" it only returns "e".

Any help is appreciated! Thanks!

CodePudding user response:

you need to return array from function and use flatMap to combine it together:

    const charsArray = ["ä", "t", "i"]
    const replaceChars = (char) => {
          switch (char) {
            case "ä":
              return ["a", "e"];
            default:
              return char;
          }
        };
    const cleanArray = charsArray.flatMap((c) => replaceChars(c));
    console.log(cleanArray);

CodePudding user response:

Immediate answer: at case "ä": return ["a", "e"];

But this is not efficient, you might want to use a Map that gives you instant access.

console.clear();
const chars = new Map();

chars.set("ä", "ae");
chars.set("ö", "oe");

const text = ["ä", "t", "i", "ö"];

const res = text.map(x => chars.get(x) || x).flatMap(x => x.split(''));

console.log(res)

CodePudding user response:

you can join it into a string and then use the String.replace() method (and then split it into an array again):

const charsArray = ["ä", "t", "i", "ü"];
const cleanArray = charsArray
  .join("")
  .replace(/ä/g, "ae")
  .replace(/ü/g, "ue")
  // you can chain as many .replace() methods as you want here
  .split("");
console.log(cleanArray);

  • Related