0

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!

3 Answers 3

1

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);

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

Comments

0

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)

Comments

0

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);

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.