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?
reduce()const arr = [ 1, 5, null, null, 10 ];
const jin = arr.reduce((p, c) => `${p},${c}`);
console.log(jin);
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);
1,5,null,null,10
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(','));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With