使用d3js排序 [英] Sorting using d3js

查看:354
本文介绍了使用d3js排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想按具有标题,价格的升序对json数据进行排序. 想要按价格排序.

I want to sort my json data in ascending order which has title, price. want to sort by price.

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

This my json data which is used in d3js.

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"}

] 

我到目前为止已经完成:

I have done so far:

 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()来对数组进行排序:

You can sort the array by passing a comparator function to .sort():

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

完整示例此处.

这篇关于使用d3js排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆