使用Javascript

时间:2016-08-30 11:39:22

标签: javascript node.js sorting

我需要使用Javascript / node将包含数组的Max Integer值从多维数组排序到第一个。

  [{"data1":8,"data2":10,"data3":20.25,"data4":0},
{"data1":12,"data2":60,"data3":14.01,"data4":0},

{"data1":30,"data2":32.19,"data3":22.51,"data4":0}]

需要输出:

  

[{ “DATA1”:12, “数据2”:60, “DATA3”:14.01, “DATA4”:0},   { “DATA1”:30 “DATA2”:32.19, “DATA3”:22.51, “DATA4”:0},   { “DATA1”:8中, “数据2”:10 “DATA3”:20.25, “DATA4”:0}]

由于第一个数组的最大值为60,第二个数组的最大值为332.19,第三个数组的最大值为20.25。

2 个答案:

答案 0 :(得分:2)

在这里。

var data= [
  {"data1":8,"data2":10,"data3":20.25,"data4":0},
  {"data1":12,"data2":60,"data3":14.01,"data4":0},
  {"data1":30,"data2":32.19,"data3":22.51,"data4":0}
];
data.sort(function(a,b){
  return Math.max(b.data1,b.data2,b.data3,b.data4)-Math.max(a.data1,a.data2,a.data3,a.data4);
});

console.log(data);

顺便问一下输出的方式是错误的.. 它应该如下:

[ { data1: 12, data2: 60, data3: 14.01, data4: 0 },
  { data1: 30, data2: 32.19, data3: 22.51, data4: 0 },
  { data1: 8, data2: 10, data3: 20.25, data4: 0 } ]

答案 1 :(得分:0)

使用W3C spec建议更大的数据集而不重复调用Sorting with map

// the array to be sorted
var data = [{ "data1": 8, "data2": 10, "data3": 20.25, "data4": 0 }, { "data1": 12, "data2": 60, "data3": 14.01, "data4": 0 }, { "data1": 30, "data2": 32.19, "data3": 22.51, "data4": 0 }];

// temporary array holds objects with position and sort-value
var mapped = data.map(function (el, i) {
        return {
            index: i, 
            value: Math.max.apply(null, Object.keys(el).map(function (k) {
                return el[k];
            }))
        };
    });

// sorting the mapped array containing the reduced values
mapped.sort(function (a, b) {
    return b.value - a.value;
});

// container for the resulting order
var result = mapped.map(function (el) {
    return data[el.index];
});

console.log(result);
console.log(mapped);
.as-console-wrapper { max-height: 100% !important; top: 0; }