Trouver la valeur max d'un attribut dans un tableau d'objets
je suis à la recherche d'un moyen vraiment rapide, propre et efficace pour obtenir la valeur max "y" dans la tranche de JSON suivante:
[{"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}]
est un for-loop le seul moyen de le contourner? J'ai envie d'utiliser Math.max
.
11 réponses
pour trouver la valeur maximale y
des objets dans array
:
Math.max.apply(Math, array.map(function(o) { return o.y; }))
Trouver l'objet dont la propriété "X" a la plus grande valeur dans un tableau d'objets
une façon serait d'utiliser le tableau réduire..
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 et au-dessus)
si vous n'avez pas besoin de supporter IE (seulement Edge), ou si vous pouvez utiliser un pré-compilateur comme Babel, vous pouvez utiliser la syntaxe plus lente.
const max = data.reduce((prev, current) => (prev.y > current.y) ? prev : current)
propre et simple ES6 (Babel)
const maxValueOfY = Math.max(...arrayToSearchIn.map(o => o.y), 0);
le second paramètre devrait assurer une valeur par défaut si arrayToSearchIn
est vide.
Eh bien, vous devez d'abord analyser la chaîne JSON, de sorte que vous pouvez facilement accéder à ses membres:
var arr = $.parseJSON(str);
utiliser la méthode map
pour extraire les valeurs:
arr = $.map(arr, function(o){ return o.y; });
alors vous pouvez utiliser le tableau dans la méthode max
:
var highest = Math.max.apply(this,arr);
ou sous la forme d'une doublure unique:
var highest = Math.max.apply(this,$.map($.parseJSON(str), function(o){ return o.y; }));
j'aimerais expliquer la réponse acceptée étape par étape:
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>');
informations complémentaires:
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}
solution ES6
Math.max(...array.map(function(o){return o.y;}))
pour plus de détails, voir https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/max
ou une sorte simple! Keeping it real :)
array.sort((a,b)=>a.y<b.y)[0].y
var max = 0;
jQuery.map(arr, function (obj) {
if (obj.attr > max)
max = obj.attr;
});
chaque tableau et obtenir la valeur max avec les mathématiques.
data.reduce((max, b) => Math.max(max, b.costo), data[0].costo);