SO-71909623
by David Thomas
HTML
<ul>
<li class="inputValue">
<textarea>1, 2300,450, 2, 2200, 920,3, 3400, 440</textarea>
<button type="button">format</button>
</li>
</ul>
CSS
*,
::before,
::after {
box-sizing: border-box;
font-family: sans-serif;
font-size: 16px;
font-weight: 400;
line-height: 1.5;
margin: 0;
padding: 0;
}
ul,
li {
list-style-type: none;
padding: 1em;
}
li {
display: flex;
flex-direction: column;
gap: 0.5em;
justify-content: space-between;
}
textarea {
min-height: 40vmin;
width: 100%;
}
JavaScript
const getResults = (evt) => {
let button = evt.currentTarget,
ancestor = button.closest('li'),
textarea = ancestor.querySelector('textarea'),
entry = textarea.value || textarea.textContent,
haystack = entry.split(/,/).map((v) => v.trim()),
result = haystack.reduce(
(acc, curr, index) => {
if (index % 3 === 0) {
let [person, posX, posY] = [...haystack].splice(index, 3);
acc.push({
person,
posX,
posY
});
}
return acc
}, []);
console.log(result);
},
buttons = document.querySelectorAll('button[type=button]');
buttons.forEach(
(btn) => btn.addEventListener('click', getResults)
);