Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

151
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!