I need your help: In Javascript I create an array with push.
for (const elem of prod[i].motor) {
if (usedMotor.includes(elem) === false) {
motor.push('<li>'+elem+'</li>');
usedMotor.push(elem);
}
}
But if I want to display it with document.getElementById('spanMotorType').innerHTML = 'Applicable Motors:'+ motor;
it is printed with comma between the elements.
Applicable Motors:
Induction motor
,
Permanent magnet motor
,
Synchronous reluctance motor
Console shows this:
Array(3) [ "<li>Induction motor</li>", "<li>Permanent magnet motor</li>",
"<li>Synchronous reluctance motor</li>" ]
0: "<li>Induction motor</li>"
1: "<li>Permanent magnet motor</li>"
2: "<li>Synchronous reluctance motor</li>"
Is there a way how I can remove this comma? The length of the Array can be between 1 and 3.
thanks
document.getElementById('spanMotorType').innerHTML = 'Applicable Motors:'+ motor.join(' ');
By default, when a string is joined with an Array, the output will print the array items with a comma, because it converts it, as-is, to string, and since there's a comma between Array items, it will also be printed:
document.write( "foo " + ['a','b','c'] )
Without commas:
document.write( "foo " + ['a','b','c'].join(' ') )
Array join converts an Array to a string with your choice of delimiter and not the default comma.
Setting Array as the innerHTML will bind the element with comma. Because Array inclueds that comma when its converted to string.
You have to make the array as a single sting and set the innerHTML to get rid of the comma.
Joing the array using Array.join, I used empty sting as the joiner. Set the innerHTML with this joined string.
const testArr = [1, 2, 3];
const myarray = testArr.map((node) => '<li>' + node + '</li>')
document.getElementById("test").innerHTML = myarray.join('');
<div id="test"></div>
So in your case it should be
document.getElementById('spanMotorType').innerHTML = 'Applicable Motors:'+ motor.join('');
Please Note
You have to mention some string with which the array is to be joined, or else , will be treated as default joiner.