0

display Arrays Object

hi i have one object : const obj = [ { name: "ahmad", family: "mahdavi", city: "kian", score: 10 }, { name: "ali", family: "Ahmadi", city: "Shahrekord", 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; } it must 2 time print onject insted 3 time. why 3 time?

17th Jul 2022, 4:56 AM
Hadi
Hadi - avatar
1 Odpowiedź
+ 1
That's because variable <txt> is defined outside of dis() function. <txt> begins with a blank string first. After you populate the array into #p1 by calling dis(), <txt> contains the data (unsorted version). When you call dis() again to populate the array into #p2, <txt> no longer is a blank string. And dis() glue more string into <txt> by adding data from the sorted array in. Solution: Define <txt> inside dis(), it is the only place where <txt> is used anyways ...
17th Jul 2022, 5:42 AM
Ipang