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:
- load this data
- log the loaded data to the console
- sort the loaded data by
distance
- 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>