pro_gamer
pro_gamer

Reputation: 194

javascript - .join method returns string joined by commas

The .join method used to solve the question returns string joined by commas.

[Question]-Repeat a given string str (first argument) for num times (second argument). Return an empty string if num is not a positive number. (The built-in repeat()-method should not be used)

function repeatStringNumTimes(str, num) {
  // repeat after me
  return num > 0 ? str.split(" ").map(function(item) {
    let a = [];
    for (let i = 0; i < num; i++) {
      a.push(item);
    }
    return a;
  }).join("") : "";
}

console.log(repeatStringNumTimes("abc", 3));

There are better ways to solve this using recursion or loops but why is the .join("") method returning string joined by commas?

link to problem

Edit -

repeatStringNumTimes("*", 8);  
repeatStringNumTimes("abc", 4);   

(these are the calls that cause the problem)

Upvotes: 1

Views: 1253

Answers (2)

liam
liam

Reputation: 1

Wouldn't it just be easier to use .replaceAll(',', ' ')? That's what I usually do for stuff like this.

Below is the same code as above but just added .replaceAll(',', ' ') after the .join.

var arrayOfArrays = [
  ["one", "two", "three"],
  ["uno", "due", "tre"],
  ["un", "deux", "trois"]
];
console.log(arrayOfArrays.join("").replaceAll(',', ' '));

Upvotes: 0

T.J. Crowder
T.J. Crowder

Reputation: 1074455

...but why is the .join("") method returning string joined by commas ?

Because the entries in the array you're returning from map are arrays, so you have an array of arrays. When you call join on an array, it implicitly uses toString on each entry of the array. The default toString on arrays uses .join(","), so each inner array becomes a comma-delimited string (and then your outer .join("") combines those with no separator between).

Here's a simple example showing the same effect using join("") on an array of arrays:

var arrayOfArrays = [
  ["one", "two", "three"],
  ["uno", "due", "tre"],
  ["un", "deux", "trois"]
];
console.log(arrayOfArrays.join(""));


split shouldn't be part of this solution at all. An array could be part of it if you like, but it certainly doesn't have to be. A simple while loop counting down num and doing string concatenation would be the simplest solution. (Lurkers: I'm intentionally not coding that for the OP, because the OP needs the opportunity to learn how to do it himself...)

Upvotes: 1

Related Questions