Reputation: 7675
The below code is working fine,
It prints:
pigs1,goats1,sheep1
pigs2,goats2,sheep2
pigs3,goats3,sheep3
My question is how can I control the delimiter between words (currently defaulted to comma)
For example to print with pound delimiter:
pigs1#goats1#sheep1
pigs2#goats2#sheep2
pigs3#goats3#sheep3
Or no delimiter ?
pigs1goats1sheep1
pigs2goats2sheep2
pigs3goats3sheep3
const animals1 = ['pigs1', 'goats1', 'sheep1'];
const animals2 = ['pigs2', 'goats2', 'sheep2'];
const animals3 = ['pigs3', 'goats3', 'sheep3'];
var buffer = [];
buffer.push(animals1);
buffer.push(animals2);
buffer.push(animals3);
console.log(buffer.join('\n'));
Upvotes: 0
Views: 762
Reputation: 5215
You can use the join
function on your arrays with any string as delimiter.
const animals1 = ['pigs1', 'goats1', 'sheep1'];
const animals2 = ['pigs2', 'goats2', 'sheep2'];
const animals3 = ['pigs3', 'goats3', 'sheep3'];
var buffer = [];
buffer.push(animals1.join('#'));
buffer.push(animals2.join('#'));
buffer.push(animals3.join('#'));
console.log(buffer.join('\n'));
Use empty string for no delimiter
animals1.join('') // pigs1goats1sheep1
EDIT:
If you don't use join
on your arrays before pushing them, you'll have an array containing array items, your buffer
looks like this:
[
[ 'pigs1', 'goats1', 'sheep1' ],
[ 'pigs2', 'goats2', 'sheep2' ],
[ 'pigs3', 'goats3', 'sheep3' ]
]
By using the final buffer.join('\n')
, the documentation says:
The string conversions of all array elements are joined into one string.
This means that the elements which are arrays are getting converted into string
[ 'pigs1', 'goats1', 'sheep1' ].toString() // 'pigs1,goats1,sheep1'
That's why you have to use join
to chose the delimiter and convert your array into string before pushing it into your buffer.
Upvotes: 4