我有一個名為的 csv 檔案text.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原始資料)未被記錄。
為什么會這樣?
謝謝!
uj5u.com熱心網友回復:
Array.prototype.sort對陣列進行就地排序。此外,您sortedData只需指向data.
因此,如果要保留兩個陣列(原始陣列和排序陣列),則必須復制它,例如使用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>
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/513943.html
上一篇:D3調整鏈接文字位置
下一篇:在Tomcat的“aQute.bnd.annotation.spi.ServiceConsumer”型別中找不到注釋方法“value()”
