Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

159
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda