Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to keep null values when using `Array.join()`?

Tags:

javascript

Consider the following,

const arr = [ 1, 5, null, null, 10 ];
console.log(arr.join(',')); // '1,5,,,10'
console.log(`${arr}`); // '1,5,,,10'

I need to keep these null values, how can I do this?

Only thing I could think of is something with reduce,

const result = arr.reduce((acc, el, index, self) => `${acc += el}${index !== self.length - 1 ? ',' : ''}`, '');

Any better way?

like image 914
Mike K Avatar asked Jul 16 '26 05:07

Mike K


2 Answers

Using reduce()

const arr = [ 1, 5, null, null, 10 ];
const jin = arr.reduce((p, c) => `${p},${c}`);

console.log(jin);

Using map() and String()

Or use map() with String function to convert each value to a string so that join() will keep it:

const arr = [ 1, 5, null, null, 10 ];
const jin = arr.map(String).join(',');

console.log(jin);

Output

1,5,null,null,10
like image 189
0stone0 Avatar answered Jul 17 '26 18:07

0stone0


Not a pretty answer, but you could turn the nulls to strings.

const arr = [ 1, 5, null, null, 10 ];
const arr2 = arr.map(x => String(x));
console.log(arr2);
console.log(arr2.join(','));
like image 30
Fractalism Avatar answered Jul 17 '26 18:07

Fractalism