Home > Mobile >  D3: only sorted data is logged to console (can't log raw data immediately after ingesting)
D3: only sorted data is logged to console (can't log raw data immediately after ingesting)

Time:09-26

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!

CodePudding user response:

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>

  • Related