Skip to content
Advertisement

Javascript: Duplicate each string value in an array

Tried googling for a while but couldn’t find my answer. I am trying to take a 3-character string and convert it to a 6-character string in which each of the 3 characters is duplicated.

For example, 3ff would become 33ffff.

First, I’m turning the string 3ff into the array ["3", "f", "f"].

After I converted to an array, I tried to map through the array and *2 each value, hoping to get the new array ["33", "ff", "ff"].

However, I am getting the new array [6, NaN, NaN].

I understand that 3 is getting multiplied by 2 for 6, and that JS doesn’t know how to multiply strings so we get NaN.

I thought that in Python, if you try to *2 a string value, it will just duplicate the value, like eggs will turn into eggseggs. Is this not the case in JS?

Here is my code:

const duplicate = function(v) {
  newArray = v.split("");
  doubledArray = newArray.map(i => i*2);
  return doubledArray
};

console.log(duplicate("3ff")) // Output: [6, NaN, NaN]

Is there a way to duplicate string values of an array in JavaScript, and not just number values?

Advertisement

Answer

You probably want to use .repeat() function like:

const duplicate = (v) => v.split("").map(i => i.repeat(2));
console.log(duplicate("3ff"));

Old notation:

const duplicate = function(v) {
    newArray = v.split("");
    doubledArray = newArray.map(i => i.repeat(2));
    return doubledArray
};
console.log(duplicate("3ff"));
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement