gpt4 book ai didi

json - 使用 d3js 排序

转载 作者:行者123 更新时间:2023-12-02 04:39:31 25 4
gpt4 key购买 nike

我想按标题、价格的升序对我的 json 数据进行排序。想按价格排序。

这是我在 d3js 中使用的 json 数据。

var data = [
{"title":"ACER Aspire DQ.SP3EK.001 ZS 605 Refurbished 19.5\u201d All-in-One PC",
"price":"<549.99"},
{"title":"LENOVO C540 23\u201d Touchscreen All-in-One PC","price":"699.99"},
{"title":"ACER Aspire V5-122P 11.6\u201d Touchscreen Laptop/u2013silver","price" :"499.99"},
{"title":"HP Pavilion 15-n097ea 15.6 Laptop \u2013 Goji Berry","price":"429.99"},
{"title":"SONY Vaio Fit 15 E SVF1521A1EW.CEK 15\u201d Laptop \u2013 White","price":"399.99"}

]

到目前为止我做了:

 var container = gallery.selectAll('.searchcontainer')
.data(data, function(d) { return d.title; });

container.enter().append('div')
.attr('class', 'searchcontainer')

container.exit().remove();

container.selectAll('ttl')
.data(function(d) { return [d]; })
.enter().append('div')
.attr('class', 'ttl')
.style('float','right')
.style('margin-top','-20px')
.style('margin-right','20px')
.style('width','80%')
.html(function(d) { return d.title; });

container.selectAll('.pricess')
.data(function(d) { return [d]; })
.enter().append('div')
.attr('class', 'pricess')
.style('float','right')
.style('width','10%')
.style('margin-bottom','10px')
.sort(d3.ascending())
.html(function(d) { return d.price; });

最佳答案

您可以通过将比较器函数传递给 .sort() 来对数组进行排序:

var container = gallery.selectAll('.searchcontainer')
.data(data.sort(function(a,b) { return +a.price - +b.price; }),
function(d) { return d.title; });

完整示例 here .

关于json - 使用 d3js 排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21185559/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com