1

I have following array like below

[1,null,null,2]

I want to implode make it as string like below

1,null,null,2

I tried

temparr.join(',')

But I am getting

1,,,2

How do i preserve the keyword null.

1
  • 1
    By replacing it with the text value null first? Or by writing your own join function, that takes your special requirement into account. Commented Feb 17, 2021 at 9:55

4 Answers 4

4

You could convert the values to string in advance, because undefined or null values are empty string by converting with join.

If an element is undefined, null or an empty array [], it is converted to an empty string.

const array = [1, null, null, 2];

console.log(array.map(String).join(','));

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

Comments

1

Map to a string first:

[1,null,null,2].map(String).join(",");

Comments

0

You can't make join do that, so you would have to change the input given to join in the first place. For example:

const result = [1, null, null, 2].map(value => value === null ? "null" : value).join(",");
console.log(result);

Comments

0

Just replace the value null by the string 'null' :

console.log([1,null,null,2].map(x => x ?? 'null').join(','))

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.