Encontrar el valor máximo de un atributo en una matriz de objetos


Estoy buscando una forma realmente rápida, limpia y eficiente de obtener el valor máximo "y" en el siguiente segmento JSON:

[{"x":"8/11/2009","y":0.026572007},{"x":"8/12/2009","y":0.025057454},{"x":"8/13/2009","y":0.024530916},{"x":"8/14/2009","y":0.031004457}]

¿Es un bucle for la única manera de hacerlo? Estoy interesado en usar de alguna manera Math.max.

Author: Seanny123, 2010-10-26

11 answers

Para encontrar el valor máximo y de los objetos en array:

Math.max.apply(Math, array.map(function(o) { return o.y; }))
 451
Author: tobyodavies,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-07-12 22:13:47

Encuentra el objeto cuya propiedad " X " tiene el mayor valor en una matriz de objetos

Una forma sería usar Array reduce..

const max = data.reduce(function(prev, current) {
    return (prev.y > current.y) ? prev : current
}) //returns object

Https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce http://caniuse.com/#search=reduce (IE9 y superior)

Si no necesita soportar IE (only Edge), o puede usar un pre-compilador como Babel, podría usar la sintaxis más concisa.

const max = data.reduce((prev, current) => (prev.y > current.y) ? prev : current)
 115
Author: Andy Polhill,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-06-28 20:33:03

ES6 limpio y simple (Babel)

const maxValueOfY = Math.max(...arrayToSearchIn.map(o => o.y), 0);

El segundo parámetro debe asegurar un valor predeterminado si arrayToSearchIn está vacío.

 64
Author: Vitaliy Kotov,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-09-10 08:49:21

Bueno, primero debes analizar la cadena JSON, para que puedas acceder fácilmente a sus miembros:

var arr = $.parseJSON(str);

Utilice el método map para extraer los valores:

arr = $.map(arr, function(o){ return o.y; });

Entonces puedes usar el array en el método max:

var highest = Math.max.apply(this,arr);

O como una sola línea:

var highest = Math.max.apply(this,$.map($.parseJSON(str), function(o){ return o.y; }));
 24
Author: Guffa,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-10-26 05:34:11

Me gustaría explicar la respuesta concisa aceptada paso a paso:

var objects = [{ x: 3 }, { x: 1 }, { x: 2 }];

// array.map lets you extract an array of attribute values
var xValues = objects.map(function(o) { return o.x; });
// es6
xValues = Array.from(objects, o => o.x);

// function.apply lets you expand an array argument as individual arguments
// So the following is equivalent to Math.max(3, 1, 2)
// The first argument is "this" but since Math.max doesn't need it, null is fine
var xMax = Math.max.apply(null, xValues);
// es6
xMax = Math.max(...xValues);

// Finally, to find the object that has the maximum x value (note that result is array):
var maxXObjects = objects.filter(function(o) { return o.x === xMax; });

// Altogether
xMax = Math.max.apply(null, objects.map(function(o) { return o.x; }));
var maxXObject = objects.filter(function(o) { return o.x === xMax; })[0];
// es6
xMax = Math.max(...Array.from(objects, o => o.x));
maxXObject = objects.find(o => o.x === xMax);


document.write('<p>objects: ' + JSON.stringify(objects) + '</p>');
document.write('<p>xValues: ' + JSON.stringify(xValues) + '</p>');
document.write('<p>xMax: ' + JSON.stringify(xMax) + '</p>');
document.write('<p>maxXObjects: ' + JSON.stringify(maxXObjects) + '</p>');
document.write('<p>maxXObject: ' + JSON.stringify(maxXObject) + '</p>');

Más información:

 18
Author: congusbongus,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 12:02:47

Si usted (o alguien aquí) es libre de usar la biblioteca de utilidades lodash, tiene una maxBy función que sería muy útil en su caso.

Por lo tanto se puede utilizar como tal:

_.maxBy(jsonSlice, 'y');
 7
Author: kmonsoor,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-10-19 07:17:02
var data = [
  { 'name': 'Vins', 'age': 27 },
  { 'name': 'Jan', 'age': 38 },
  { 'name': 'Alex', 'age': 80 },
  { 'name': 'Carl', 'age': 25 },
  { 'name': 'Digi', 'age': 40 }
];
var max = data.reduce(function (prev, current) {
   return (prev.age > current.age) ? prev : current
});
//output = {'name': 'Alex', 'age': 80}
 4
Author: Vin S,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-06-08 06:24:29

Solución ES6

Math.max(...array.map(function(o){return o.y;}))

Para más detalles, ver https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/max

 2
Author: ndey96,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-09-28 21:19:20

O un tipo simple! Manteniéndolo real:)

array.sort((a,b)=>a.y<b.y)[0].y
 2
Author: Ooki Koi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-01-10 10:45:04
var max = 0;                
jQuery.map(arr, function (obj) {
  if (obj.attr > max)
    max = obj.attr;
});
 1
Author: Mephisto07,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-08-26 12:39:15

Cada matriz y obtener el valor máximo con Matemáticas.

data.reduce((max, b) => Math.max(max, b.costo), data[0].costo);
 1
Author: Diego Santa Cruz Mendezú,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-07-12 13:22:03