1

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

3 Answers 3

1

Write it as follows:

document.getElementById('spanMotorType').innerHTML = 'Applicable Motors:'+ motor.join(' ');

Explanation:

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.

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

1 Comment

thank you! It looks so easy and i tried so long with replace, splice and all that. Join works perfectly!
1

Use following code.

usermotor.join(" ")

https://sebhastian.com/javascript-array-string/

Comments

1

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.

1 Comment

I can't vote yet, so thank you too for your helpful reply!

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.