5

I want to join an array of result = ["July"," ","1st"] into result = ["July 1st"]. I also want to have the comma removed.

I have tried result.join() and result.join(",") but it didn't work. In fact, nothing changes. Can anyone help me to solve this problem? Thanks.

4
  • 1
    Are you referencing the output? Those calls will not change the result variable. var joined = result.join(""); Commented Jun 22, 2016 at 3:10
  • 1
    result = result[0]+result[1]+result[2] Commented Jun 22, 2016 at 3:10
  • codepen for reference-codepen.io/nagasai/pen/ezBvyG Commented Jun 22, 2016 at 3:12
  • Are you sure you want a single element result array? What good does this result do? Commented Mar 22, 2022 at 14:00

4 Answers 4

3

You just need to join it and put into an array...:

result = [result.join('')];
Sign up to request clarification or add additional context in comments.

3 Comments

it works when I create a new variable and assign the result to it. I wonder why it didnt work this way result = result.join('');
Then just assign it to the result. I updated my answer.
I see, so we have to put the result.join('') inside a [ ] to make it work. Thanks
1

You need to specify empty string in .join function

var result = ["July"," ","1st"]
result.join('') // "July 1st"

EDIT: and if you need output in array then it will

[result.join('')] // ["July 1st"]

Comments

0

var b ="";

result.forEach(function(a){b = b.concat(a);});

console.log(b);

Comments

0

You can also use the javascript reduce() function as follows:

var result = [result.reduce(function(previousString, currentString) {
                return previousString + currentString 
             })];

For a more detailed explanation of how it works, check out this video by Mattias Petter Johansson

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.