I have one array object.
I want to display it before and after sorting it.
My code is:
const obj = [
{ name: "ahmad", family: "mahdavi", city: "esf", score: 10 },
{ name: "ali", family: "Ahmadi", city: "ahv", score: 5 },
{ name: "reza", family: "rezaei", city: "tehran", score: 3 },
{ name: "mohammad", family: "kiani", city: "shiraz", score: 19 }
];
let txt = "";
document.getElementById("p1").innerHTML = dis();
obj.sort(
function (a, b) {
return a.score - b.score;
}
)
document.getElementById("p2").innerHTML = dis();
function dis() {
obj.forEach(element => {
txt += element.name + " " + element.family + " " + element.city + " " + element.score + "<br>";
})
return txt;
}
<p id="p1"></p>
<p id="p2"></p>
It should display the data 2 times, but it displays it 3 times. Why?