JSFiddle - React, Tailwind, and code Playground
HTML
<div id='div' style='width:100px; padding:10px; background:green;
white-space: nowrap; '>
<span id='span' style='background:yellow; text-overflow: ellipsis;'></span>
</div>
JavaScript
const exampleArray = ['Germany','Australia','Canada','Mongolia','Argentina','China'];
function addToDiv(arr) {
const div = document.querySelector("#div");
const span = div.firstElementChild;
const divWidth = div.clientWidth;
let finalIndex = '';
let remaining = 0;
for (const [index,c] of arr.entries())
{
span.append(c)
if(span.offsetWidth >= divWidth){
finalIndex = index-1;
remaining = arr.length - index;
break;
}
if(index != arr.length -1)
span.append(', ')
}
if(!remaining) return;
span.textContent = '';
for (const [index,c] of arr.entries())
{
if(index > finalIndex) break;
span.append(c+', ')
}
span.append('...'+remaining)
}
addToDiv(exampleArray);