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

178
Visualizações
How to check redundancy in for loop

I am pulling some information from an API and one of my fields may or may not have duplicate content. How do I identify the redundancy and not print it on the screen if it's a duplicate?

Here's my loop, and "Description" is the field that sometimes has the same content as its previous sibling:

for (i = 0; i < data.length; i++) {
    htmlString += '<li><h3 class="session-item">' + data[i].Title + '</h3>';
    htmlString += '<p class="session-description">' + data[i].Description + '</p></li>';
}

Is this something I should check/compare with the previous sibling or is there a better way?

I tried a simple comparison but this didn't work:

var tempDesc = document.getElementsByClassName('session-description');
for (i = 0; i < data.length; i++) {
    htmlString += '<li><h3 class="session-item">' + data[i].Title + '</h3>';
    if(tempDesc === data[i].Description) {
        htmlString += '</li>';
    } esle {
        htmlString += '<p class="session-description">' + data[i].Description + '</p></li>';
    }
}
about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

You already have the index so a simple solution is to get the last index with i - 1:

for (i = 0; i < data.length; i++) {
    htmlString += '<li><h3 class="session-item">' + data[i].Title + '</h3>';
    

    if (data[i].Description !== data[i - 1].Description) {
        htmlString += '<p class="session-description">' + data[i].Description + '</p></li>';
    } else {
        htmlString += '</li>';
    }
}

But you want to check if it data[i - 1] exists first:

if (data[i].Description !== (data[i - 1] && data[i - 1].Description)) {

If you want a shorter answer then you could use the more advanced optional chaining:

if (data[i].Description !== data[i - 1]?.Description) {
about 4 years ago · Juan Pablo Isaza Relatório

0

const isEqual = (...objects) => objects.every(obj => JSON.stringify(obj) === JSON.stringify(objects[0]));
data.reduce((x,y) => (x.filter(x => isEqual(x, y)).length > 0) ? x : x.concat([y]), []);

then, use data with every way you want, all elements are unique :)

about 4 years ago · Juan Pablo Isaza Relatório

0

Presuming your dataset looks something like this:

const apiResponse = [
  { Title: 'Sanity and Tallulah', Description: 'Description 1' },
  { Title: 'Zita the Space Girl', Description: 'Description 2' },
  { Title: 'Lumberjanes', Description: 'Description 1' },
];

...and I am understanding your goal correctly that you want to suppress duplicate descriptions but keep the titles, I would suggest one approach is to use a Set as you are looping to add to the DOM, and check to see if the description is already present in the Set before writing it. Something like:

const apiResponse = [
  { Title: 'Sanity and Tallulah', Description: 'Description 1' },
  { Title: 'Zita the Space Girl', Description: 'Description 2' },
  { Title: 'Lumberjanes', Description: 'Description 1' },
];

const descriptions = new Set();

for (let item of apiResponse) {
    document.body.append(item.Title)
    document.body.append(document.createElement('br'))
    if (!descriptions.has(item.Description)) {
      descriptions.add(item.Description);
      document.body.append(item.Description)
      document.body.append(document.createElement('br'))
      document.body.append(document.createElement('br'))
    }
}

This approach would allow a single loop and avoid having to do comparisons in/against the DOM as a source of truth.

Another option (explored in other answers already) is to first loop the responses and eliminate duplicate values and then loop to push to the DOM.

about 4 years ago · Juan Pablo Isaza 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