将对象数组推入数组进行排序

时间:2018-09-10 07:11:55

标签: javascript arrays object

发现无法对对象进行排序后-即使我需要排序的对象的值-我相信我必须将对象数组的内容推入数组进行排序。

下面的代码产生此输出,而没有实现任何发送到数组的功能:

enter image description here

这是我的代码:

var aveArr = {};
var length = 0;
var q = d3.queue();
['csv goes here', 'another csv goes here'].map((c) => {
  q.defer(d3.csv, c);
  length += 1;
});

q.awaitAll(function(d, csvs){
    var selection = d3.merge(csvs);

    selection.map((d,i) => {
      aveArr[d.word] = {
        sum: 0,
        average: 0,
    };  

    var obj = aveArr[d.word];
    obj.sum += +d.frequency;
    obj.average = obj.sum / length;
});

  console.log(aveArr); 

});

我只需要在控制台中显示单词和平均值,然后对平均值进行排序即可。

我发现this用于将内容推送到数组,但是对我来说,它不起作用。

2 个答案:

答案 0 :(得分:2)

目前,您正在通过在其上设置键来将“数组”用作对象。 我建议更改数据结构,以便它是具有固定字段的真实数组。 然后排序和转换变得非常简单:

//	source data
const data = [
  { name: "0", sum: 0, average: 0 },
  { name: "001", sum: 0, average: 0 },
  { name: "00", sum: 1, average: 0.5 },
  { name: "01", sum: 0, average: 0 },
  { name: "1", sum: 11, average: 5.5 },
  { name: "1am", sum: 0, average: 0 },
  { name: "1pickford", sum: 0, average: 0 },
  { name: "1pm", sum: 0, average: 0 },
  { name: "1pm2", sum: 0, average: 0 },
  { name: "1st", sum: 3, average: 1.5 },
  { name: "1x", sum: 2, average: 1 },
  { name: "1xbet", sum: 0, average: 0 }
];
const transformed = data
  //	we only want the name and average
  .map(({ name, sum, average }) => ({ name, average }))
  //	sort by average
  .sort(( a, b ) => a.average - b.average );

console.log( transformed );

答案 1 :(得分:1)

您要保留对象结构吗?

const aveArr = {
  '0': { sum: 0, average: 0 },
  '001': { sum: 0, average: 0 },
  '00': { sum: 1, average: 0.5 },
  '01': { sum: 0, average: 0 },
  '1': { sum: 11, average: 5.5 },
  '1am': { sum: 0, average: 0 },
  '1pickford': { sum: 0, average: 0 },
  '1pm': { sum: 0, average: 0 },
  '1pm': { sum: 0, average: 0 },
  '1st': { sum: 3, average: 1.5 },
  '1x': { sum: 2, average: 1 },
  '1xbet': { sum: 0, average: 0 }
};

const transformed = Object
  .keys(aveArr).map(key => ({ name: key, average: aveArr[key].average }));
  
const sorted = transformed.sort((left, right) => left.average - right.average);

console.log(sorted);