我使用D3.JS作为我的项目,我不确定如何对传入的数据进行排序。我的API中有以下内容:
[
{
"target": "target_one",
"datapoints": [
[
8.0,
1493510400.0
],
[
8.0,
1493596800.0
]
]
},
{
"target": "target_two",
"datapoints": [
[
1.0,
1493510400.0
],
[
1.0,
1493596800.0
],
[
10.0,
1493683200.0
]
]
},
]
有没有办法使用d3我可以将这些数据从高到低排序?任何建议都会很棒,谢谢!
答案 0 :(得分:-1)
您可以使用原始javascript,使用此原型函数
执行此操作Array.prototype.orderByDescending = function (func) {
this.sort((a, b) => {
var a = func(a);
var b = func(b);
if (typeof a === 'string' || a instanceof String) {
return b.localeCompare(a);
}
return b - a;
});
return this;
}
并像那样调用它
elements.forEach(element=>{ element.datapoints.orderByDescending(p => p[0]) })
或者如果您不想污染原型,可以使用普通功能
function orderByDescending (array,func) {
array.sort((a, b) => {
var a = func(a);
var b = func(b);
if (typeof a === 'string' || a instanceof String) {
return b.localeCompare(a);
}
return b - a;
});
return array;
}
并像那样调用它
elements.forEach(element=>{ orderByDescending(element.datapoints, p =>p [0])})
片段
Array.prototype.orderByDescending = function (func) {
this.sort((a, b) => {
var a = func(a);
var b = func(b);
if (typeof a === 'string' || a instanceof String) {
return b.localeCompare(a);
}
return b - a;
});
return this;
}
var elements = [
{
"target": "target_one",
"datapoints": [
[
8.0,
1493510400.0
],
[
8.0,
1493596800.0
]
]
},
{
"target": "target_two",
"datapoints": [
[
1.0,
1493510400.0
],
[
1.0,
1493596800.0
],
[
10.0,
1493683200.0
]
]
},
]
// order by [0] point
elements.forEach(element=>{
element.datapoints.orderByDescending(p=>p[0])
})
console.log('ordered descending by first element')
console.log(JSON.stringify(elements));
// order by [1] point
elements.forEach(element=>{
element.datapoints.orderByDescending(p=>p[1])
})
console.log('ordered descending by second element')
console.log(JSON.stringify(elements));