Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

display Array Object in js

I have one array object.

I want to display it before and after sorting it.

My code is:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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;
}
<p id="p1"></p>

<p id="p2"></p>

It should display the data 2 times, but it displays it 3 times. Why?

>Solution :

This happens because your txt variable is global and keeps collecting data. You should make it a local variable, so that it starts from scratch each time you call dis:

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 }
];

document.getElementById("p1").innerHTML = dis();

obj.sort(
    function (a, b) {
        return a.score - b.score;
    }
)

document.getElementById("p2").innerHTML = dis();


function dis() {
    var txt = ""; // <---
    obj.forEach(element => {
        txt += element.name + " " + element.family + " " + element.city + " " + element.score + "<br>";
    })
    return txt;
}
<p id="p1"></p>

<p id="p2"></p>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading