I have a fetch from an API (sorted alphabetically) which I have put in an array ("peopleArray"). This array I iterate over in a forEach.
I want to be able to reverse the order of the list. However, every time a click my "sorting"-button the list duplicates itself in the reverse order.
How do I get it to rewrite/replace/rearrange the original list instead of adding a new reversed one? What am I missing in my sorting?
This is my original forEach
peopleArray.forEach((person) => {
cardbox.innerHTML = `
<div >
<img src="${person.picture.medium}" alt="picture" />
<span ></span>
<span ></span>
<div >
<div >
<p >${person.name.first} ${person.name.last}</p>
<p >${person.location.city}</p>
</div>
<div >
<a href="mailto:${person.email}"> <i ></i></a>
<a href="tel:${person.phone}"><i ></i></a>
</div>
</div>
</div>
And this is the sorting-function/ forEach
sort.addEventListener("click", function () {
peopleArray.reverse();
peopleArray.forEach((person) => {
cardbox.innerHTML = `
<div >
<img src="${person.picture.medium}" alt="picture" />
<div >
<div >
<p >${person.name.first} ${person.name.last}</p>
<p >${person.location.city}</p>
</div>
<div >
<a href="mailto:${person.email}"> <i ></i></a>
<a href="tel:${person.phone}"><i ></i></a>
</div>
</div>
</div>
`;
});
});
CodePudding user response:
You need to clear the list before appending new elements.
sort.addEventListener("click", function () {
peopleArray.reverse();
cardbox.innerHTML = '';
peopleArray.forEach((person) => {
cardbox.innerHTML = `...`
}
CodePudding user response:
As the content is already rendered on your page your reverse function can be greatly simplified, see below:
const cont=document.getElementById("someContainer");
document.querySelector("button").onclick=ev=>[...cont.children].reverse().forEach(div=>cont.append(div));
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.0/css/all.min.css"/>
<button>reverse list</button>
<div id="someContainer">
<div >
<img src="https://picsum.photos/id/201/200/120" alt="picture" />
<span ></span>
<span ></span>
<div >
<div >
<p >Harry Potter</p>
<p >Wisteria Lane</p>
</div>
<div >
<a href="mailto:[email protected]"> <i ></i></a>
<a href="tel: 44 007"><i ></i></a>
</div>
</div>
</div>
<div >
<img src="https://picsum.photos/id/202/200/120" alt="picture" />
<span ></span>
<span ></span>
<div >
<div >
<p >Ron Weasley</p>
<p >Diagon Alley</p>
</div>
<div >
<a href="mailto:[email protected]"> <i ></i></a>
<a href="tel: 44 0815"><i ></i></a>
</div>
</div>
</div>
<div >
<img src="https://picsum.photos/id/203/200/120" alt="picture" />
<span ></span>
<span ></span>
<div >
<div >
<p >Hermione Granger</p>
<p >Muggle Land</p>
</div>
<div >
<a href="mailto:[email protected]"> <i ></i></a>
<a href="tel: 44 4711"><i ></i></a>
</div>
</div>
</div>
</div>