Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

95
Visualizações
display Array Object in js

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?

about 4 years ago · Santiago Gelvez
1 Respostas
Responde à pergunta

0

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>

about 4 years ago · Santiago Gelvez Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda