d3.js:对嵌套数组进行排序

时间:2018-09-05 14:18:20

标签: javascript

我如何对下面的数组的嵌套数组进行排序?我想对数组prob进行排序,然后相应地重新排列name,以便保持关系。

var records = [
{ num: 1, name: ["Sam", "Amy", "John"], prob: [0.3, 0.2, 0.5]},
{ num: 2, name: ["Nick", "Carol", "Sam"], prob: [0.5, 0.03, 0.47] },
{ num: 3, name: ["Ken", "Eric", "Ely"], prob: [0.1, 0.3, 0.6] },
{ num: 4, name: ["Amy", "Sam", "John"], prob: [0.6, 0.3, 0.1] },
{ num: 5, name: ["Chris", "Donna", "Jeff"], prob: [0.25, 0.55, 0.2] }
]

我想结束:

var records = [
{ num: 1, name: ["John", "Sam", "Amy"], prob: [0.5, 0.3, 0.2]},
{ num: 2, name: ["Nick", "Sam", "Carol"], prob: [0.5, 0.47, 0.03] },
{ num: 3, name: ["Ely", "Eric", "Ken"], prob: [0.6, 0.3, 0.1] },
{ num: 4, name: ["Amy", "Sam", "John"], prob: [0.6, 0.3, 0.1] },
{ num: 5, name: ["Donna", "Chris", "Jeff"], prob: [0.55, 0.25, 0.2] }
]

谢谢!

3 个答案:

答案 0 :(得分:1)

最简单的方法是将nameprob的数组转换为对象以保留每个名称和概率之间的链接。然后可以使用自定义排序功能将对象的属性像数组一样进行排序。

records.forEach( function (d) {
  var temp = {};

  // create objects with key <name> and value <prob>
  // (this makes the assumption that prob values may not be unique, but names are)
  d.name.forEach( function(e,i) {
    temp[e] = d.prob[i];
  })

  // get an array of the object keys (the name), and sort them by the object values
  // (the corresponding prob), descending. Replace the existing `name` array with this.
  d.name = Object.keys(temp).sort(function(a, b){ 
    return temp[b] - temp[a];
  });

  // sort the prob values in descending order (with d3.descending, since you mentioned d3)
  d.prob = d.prob.sort(function(a,b){ return b - a; });
});

如果您不使用d3,请用标准降序排序功能替换d3.descending

答案 1 :(得分:1)

这是一个解决方案:我们可以将namesprob存储在pairs中,并同时对两个值进行排序,然后将已排序的名称和概率分配给主对象:< / p>

var records = [
{ num: 1, name: ["Sam", "Amy", "John"], prob: [0.3, 0.2, 0.5]},
{ num: 2, name: ["Nick", "Carol", "Sam"], prob: [0.5, 0.03, 0.47] },
{ num: 3, name: ["Ken", "Eric", "Ely"], prob: [0.1, 0.3, 0.6] },
{ num: 4, name: ["Amy", "Sam", "John"], prob: [0.6, 0.3, 0.1] },
{ num: 5, name: ["Chris", "Donna", "Jeff"], prob: [0.25, 0.55, 0.2] }
];

var pairs = records.map((e,i)=>
e.name.map((e2,i2)=>[e2,records[i].prob[i2]]).sort((a,b)=>b[1]-a[1])
);

records.map((e, i) => {
  e.name = pairs[i].map(o => o[0])
  e.prob = pairs[i].map(o => o[1])      
})

console.log(records)

答案 2 :(得分:1)

重构Emeeus答案

var records = [
{ num: 1, name: ["Sam", "Amy", "John"], prob: [0.3, 0.2, 0.5]},
{ num: 2, name: ["Nick", "Carol", "Sam"], prob: [0.5, 0.03, 0.47] },
{ num: 3, name: ["Ken", "Eric", "Ely"], prob: [0.1, 0.3, 0.6] },
{ num: 4, name: ["Amy", "Sam", "John"], prob: [0.6, 0.3, 0.1] },
{ num: 5, name: ["Chris", "Donna", "Jeff"], prob: [0.25, 0.55, 0.2] }
];

records.forEach((e, i) => {
  var el = e.name.map((e2,i2)=>[e2,e.prob[i2]]);
  el.sort((a, b) => b[1] - a[1]);
  e.name = el.map(o => o[0]);
  e.prob = el.map(o => o[1]);
});

console.log(records);