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

150
Visualizações
D3: only sorted data is logged to console (can't log raw data immediately after ingesting)

I have a csv file named text.csv that contains the following:

shape,color,distance
circle,blue,4
square,red,2
circle,blue,7
circle,green,9
triangle,blue,1
square,green,3
octagon,blue,4

I want to do the following:

  1. load this data
  2. log the loaded data to the console
  3. sort the loaded data by distance
  4. log the sorted data

Here is my code:

<script src="https://d3js.org/d3.v7.min.js"></script>

d3.csv('test.csv', d3.autoType).then(function(data) {
    // INSPECTS THE RAW DATA
    console.log(data);

    // SORTS BY DISTANCE
    let sortedData = data.sort(function (a, b) {
        return d3.descending(a.distance, b.distance);
    })
    // LOGS SORTED DATA
    console.log(sortedData);
})

In the console, I see that sortedData is logged twice.

The data variable (i.e. the raw unsorted data) is not being logged.

Why is this happening?

Thanks!

almost 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

Array.prototype.sort sorts the array in place. Also, your sortedData simply points to data.

Therefore, if you want to keep two arrays (the original and the sorted one), you have to duplicate it, for instance using structuredClone:

const csv = `shape,color,distance
circle,blue,4
square,red,2
circle,blue,7
circle,green,9
triangle,blue,1
square,green,3
octagon,blue,4`;

const data = d3.csvParse(csv, d3.autoType);
console.log(data);

// SORTS BY DISTANCE
let sortedData = structuredClone(data).sort(function(a, b) {
  return d3.descending(a.distance, b.distance);
})
// LOGS SORTED DATA
console.log(sortedData);
<script src="https://d3js.org/d3.v7.min.js"></script>

almost 4 years ago · Santiago Trujillo 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