GaneshKumar GaneshKumar - 3 months ago 14
Javascript Question

Get max value from multidimensional array using Javascript

I need to sort the Max Integer value containing array from the Multidimensional array to the first using Javascript / node.

[{"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}]


Need Output:


[{"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}]


Since 1st array has maximum value 60, second has 332.19 and third array has maximum value 20.25.

Answer

Here it is.

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);

By the way output in the question is wrong.. it should be as follow:

[ { 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 } ]
Comments