[英]D3: only sorted data is logged to console (can't log raw data immediately after ingesting)
我有一個名為text.csv
的 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
我想做以下事情:
distance
對加載的數據進行排序這是我的代碼:
<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);
})
在控制台中,我看到 sortedData 被記錄了兩次。
未記錄data
變量(即原始未排序數據)。
為什么會這樣?
謝謝!
Array.prototype.sort
對數組進行就地排序。 此外,您的sortedData
只是指向data
。
因此,如果你想保留兩個 arrays (原始的和排序的),你必須復制它,例如使用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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.