Finding the max value of an attribute in an array of objects
JavascriptJsonJavascript Problem Overview
I'm looking for a really quick, clean and efficient way to get the max "y" value in the following JSON slice:
[ { "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 }]
Is a for-loop the only way to go about it? I'm keen on somehow using Math.max
.
Javascript Solutions
Solution 1 - Javascript
To find the maximum y
value of the objects in array
:
Math.max.apply(Math, array.map(function(o) { return o.y; }))
or in more modern JavaScript:
Math.max(...array.map(o => o.y))
Solution 2 - Javascript
Find the object whose property "Y" has the greatest value in an array of objects
One way would be to use 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 and above)
If you don't need to support IE (only Edge), or can use a pre-compiler such as Babel you could use the more terse syntax.
const max = data.reduce((prev, current) => (prev.y > current.y) ? prev : current)
Solution 3 - Javascript
clean and simple ES6 (Babel)
const maxValueOfY = Math.max(...arrayToSearchIn.map(o => o.y), 0);
The second parameter should ensure a default value if arrayToSearchIn
is empty.
Solution 4 - Javascript
Comparison of three ONELINERS which handle minus numbers case (input in a
array):
var maxA = a.reduce((a,b)=>a.y>b.y?a:b).y; // 30 chars time complexity: O(n)
var maxB = a.sort((a,b)=>b.y-a.y)[0].y; // 27 chars time complexity: O(nlogn)
var maxC = Math.max(...a.map(o=>o.y)); // 26 chars time complexity: >O(2n)
editable example here. Ideas from: maxA, maxB and maxC (side effect of maxB is that array a
is changed because sort
is in-place).
var a = [ {"x":"8/11/2009","y":0.026572007},{"x":"8/12/2009","y":0.025057454}, {"x":"8/14/2009","y":0.031004457},{"x":"8/13/2009","y":0.024530916}]
var maxA = a.reduce((a,b)=>a.y>b.y?a:b).y;
var maxC = Math.max(...a.map(o=>o.y));
var maxB = a.sort((a,b)=>b.y-a.y)[0].y;
document.body.innerHTML=`<pre>maxA: ${maxA}\nmaxB: ${maxB}\nmaxC: ${maxC}</pre>`;
For bigger arrays the Math.max...
will throw exception: Maximum call stack size exceeded (Chrome 76.0.3809, Safari 12.1.2, date 2019-09-13)
let a = Array(400*400).fill({"x": "8/11/2009", "y": 0.026572007 });
// Exception: Maximum call stack size exceeded
try {
let max1= Math.max.apply(Math, a.map(o => o.y));
} catch(e) { console.error('Math.max.apply:', e.message) }
try {
let max2= Math.max(...a.map(o=>o.y));
} catch(e) { console.error('Math.max-map:', e.message) }
Solution 5 - Javascript
I'd like to explain the terse accepted answer step-by-step:
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>');
Further information:
Solution 6 - Javascript
Well, first you should parse the JSON string, so that you can easily access it's members:
var arr = $.parseJSON(str);
Use the map
method to extract the values:
arr = $.map(arr, function(o){ return o.y; });
Then you can use the array in the max
method:
var highest = Math.max.apply(this,arr);
Or as a one-liner:
var highest = Math.max.apply(this,$.map($.parseJSON(str), function(o){ return o.y; }));
Solution 7 - Javascript
Here is the shortest solution (One Liner) ES6:
Math.max(...values.map(o => o.y));
Solution 8 - Javascript
if you (or, someone here) are free to use lodash
utility library, it has a maxBy function which would be very handy in your case.
hence you can use as such:
_.maxBy(jsonSlice, 'y');
Solution 9 - Javascript
Or a simple sort! Keeping it real :)
array.sort((a,b)=>a.y<b.y)[0].y
Solution 10 - Javascript
Each array and get max value with Math.
data.reduce((max, b) => Math.max(max, b.costo), data[0].costo);
Solution 11 - Javascript
var max = 0;
jQuery.map(arr, function (obj) {
if (obj.attr > max)
max = obj.attr;
});
Solution 12 - Javascript
ES6 solution
Math.max(...array.map(function(o){return o.y;}))
For more details see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/max
Solution 13 - Javascript
It returns the object simplified @andy polhill answare
var data=[
{
y:90
},
{
y:9
},
{
y:8
}
]
const max = data.reduce((prev, current)=> ( (prev.y > current.y) ? prev : current),0) //returns object
console.log(max)
Solution 14 - Javascript
Quick and dirty:
Object.defineProperty(Array.prototype, 'min',
{
value: function(f)
{
f = f || (v => v);
return this.reduce((a, b) => (f(a) < f(b)) ? a : b);
}
});
Object.defineProperty(Array.prototype, 'max',
{
value: function(f)
{
f = f || (v => v);
return this.reduce((a, b) => (f(a) > f(b)) ? a : b);
}
});
console.log([1,2,3].max());
console.log([1,2,3].max(x => x*(4-x)));
console.log([1,2,3].min());
console.log([1,2,3].min(x => x*(4-x)));
Solution 15 - Javascript
Explanation for accepted answer and a more generalized way
If someone's here to find the max value among all such keys (a generalized way):
const temp1 = [
{
"name": "Month 8 . Week 1",
"CATEGORY, Id 0": null,
"CATEGORY, Id 1": 30.666666666666668,
"CATEGORY, Id 2": 17.333333333333332,
"CATEGORY, Id 3": 12.333333333333334,
"TASK, Id 1": 30.666666666666668,
"TASK, Id 2": 12.333333333333334,
"TASK, Id 3": null,
"TASK, Id 4": 5,
"TASK, Id 5": null,
"TASK, Id 6": null,
"TASK, Id 7": null,
"TASK, Id 8": null,
"TASK, Id 9": null,
"TASK, Id 10": null,
"TASK, Id 12": null,
"TASK, Id 14": null,
"TASK, Id 16": null,
"TASK, Id 17": null,
"TASK, Id 26": 12.333333333333334
},
{
"name": "Month 8 . Week 2",
"CATEGORY, Id 0": 38,
"CATEGORY, Id 1": null,
"CATEGORY, Id 2": 12,
"CATEGORY, Id 3": null,
"TASK, Id 1": null,
"TASK, Id 2": 15,
"TASK, Id 3": null,
"TASK, Id 4": null,
"TASK, Id 5": null,
"TASK, Id 6": 5,
"TASK, Id 7": 5,
"TASK, Id 8": 5,
"TASK, Id 9": 5,
"TASK, Id 10": null,
"TASK, Id 12": null,
"TASK, Id 14": null,
"TASK, Id 16": null,
"TASK, Id 17": null,
"TASK, Id 26": 15
},
{
"name": "Month 8 . Week 3",
"CATEGORY, Id 0": 7,
"CATEGORY, Id 1": 12.333333333333334,
"CATEGORY, Id 2": null,
"CATEGORY, Id 3": null,
"TASK, Id 1": null,
"TASK, Id 2": null,
"TASK, Id 3": 12.333333333333334,
"TASK, Id 4": null,
"TASK, Id 5": null,
"TASK, Id 6": null,
"TASK, Id 7": null,
"TASK, Id 8": null,
"TASK, Id 9": null,
"TASK, Id 10": null,
"TASK, Id 12": null,
"TASK, Id 14": 7,
"TASK, Id 16": null,
"TASK, Id 17": null,
"TASK, Id 26": null
},
{
"name": "Month 8 . Week 4",
"CATEGORY, Id 0": null,
"CATEGORY, Id 1": null,
"CATEGORY, Id 2": 10,
"CATEGORY, Id 3": 5,
"TASK, Id 1": null,
"TASK, Id 2": null,
"TASK, Id 3": null,
"TASK, Id 4": null,
"TASK, Id 5": 5,
"TASK, Id 6": null,
"TASK, Id 7": null,
"TASK, Id 8": null,
"TASK, Id 9": null,
"TASK, Id 10": 5,
"TASK, Id 12": 5,
"TASK, Id 14": null,
"TASK, Id 16": null,
"TASK, Id 17": null,
"TASK, Id 26": null
},
{
"name": "Month 8 . Week 5",
"CATEGORY, Id 0": 5,
"CATEGORY, Id 1": null,
"CATEGORY, Id 2": 7,
"CATEGORY, Id 3": null,
"TASK, Id 1": null,
"TASK, Id 2": null,
"TASK, Id 3": null,
"TASK, Id 4": null,
"TASK, Id 5": null,
"TASK, Id 6": null,
"TASK, Id 7": null,
"TASK, Id 8": null,
"TASK, Id 9": null,
"TASK, Id 10": null,
"TASK, Id 12": null,
"TASK, Id 14": null,
"TASK, Id 16": 7,
"TASK, Id 17": 5,
"TASK, Id 26": null
},
{
"name": "Month 9 . Week 1",
"CATEGORY, Id 0": 13.333333333333334,
"CATEGORY, Id 1": 13.333333333333334,
"CATEGORY, Id 3": null,
"TASK, Id 11": null,
"TASK, Id 14": 6.333333333333333,
"TASK, Id 17": null,
"TASK, Id 18": 7,
"TASK, Id 19": null,
"TASK, Id 20": null,
"TASK, Id 26": 13.333333333333334
},
{
"name": "Month 9 . Week 2",
"CATEGORY, Id 0": null,
"CATEGORY, Id 1": null,
"CATEGORY, Id 3": 13.333333333333334,
"TASK, Id 11": 5,
"TASK, Id 14": null,
"TASK, Id 17": 8.333333333333334,
"TASK, Id 18": null,
"TASK, Id 19": null,
"TASK, Id 20": null,
"TASK, Id 26": null
},
{
"name": "Month 9 . Week 3",
"CATEGORY, Id 0": null,
"CATEGORY, Id 1": 14,
"CATEGORY, Id 3": null,
"TASK, Id 11": null,
"TASK, Id 14": null,
"TASK, Id 17": null,
"TASK, Id 18": null,
"TASK, Id 19": 7,
"TASK, Id 20": 7,
"TASK, Id 26": null
}
]
console.log(Math.max(...[].concat([], ...temp1.map(i => Object.values(i))).filter(v => typeof v === 'number')))
one thing to note that Math.max(1, 2, 3)
returns 3
.
So does Math.max(...[1, 2, 3])
, since Spread syntax can be used when all elements from an object or array need to be included in a list of some kind.
We will take advantage of this!
Let's assume an array which looks like:
var a = [{a: 1, b: 2}, {foo: 12, bar: 141}]
And the goal is to find the max (among any attribute), (here it is bar
(141))
so to use Math.max()
we need values in one array (so we can do ...arr
)
First let's just separate all the numbers
We can each that each item of the array a
is an object.
While iterating through each of them, Object.values(item)
will give us all the values of that item in an array form, and we can use map
to generate a new array with only values
So,
var p = a.map(item => Object.values(item)) // [ [1, 2], [12, 141] ]
Also,using concat,
So,
var f = [].concat(...p) // [1, 2, 12, 141]
since we have now an array of just numbers we do Math.max(...f):
var m = Math.max(...f) // 141
Solution 16 - Javascript
Thanks for the answers I found here, I hope it can be useful to someone. This typescript function can be called to search for the largest value that can exist in a field of the objects of an array:
function getHighestField(objArray: any[], fieldName: string) {
return Number(
Math.max.apply(
Math,
objArray?.map(o => o[fieldName] || 0),
) || 0,
);
}
With this values as an example:
const scoreBoard = [
{ name: 'player1', score: 4 },
{ name: 'player2', score: 9 },
{ name: 'player3', score: 7 }
]
You can call the function something this way:
const myHighestVariable = `This is the highest: ${getHighestField(scoreBoard, "score")}`;
The result will be something like this:
console.log(myHighestVariable);
> This is the highest: 9
Solution 17 - Javascript
// Here is very simple way to go:
// Your DataSet.
let numberArray = [
{
"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
}
]
// 1. First create Array, containing all the value of Y
let result = numberArray.map((y) => y)
console.log(result) // >> [0.026572007,0.025057454,0.024530916,0.031004457]
// 2.
let maxValue = Math.max.apply(null, result)
console.log(maxValue) // >> 0.031004457
Solution 18 - Javascript
It's very simple
const array1 = [
{id: 1, val: 60},
{id: 2, val: 2},
{id: 3, val: 89},
{id: 4, val: 78}
];
const array2 = [1,6,8,79,45,21,65,85,32,654];
const max = array1.reduce((acc, item) => acc = acc > item.val ? acc : item.val, 0);
const max2 = array2.reduce((acc, item) => acc = acc > item ? acc : item, 0);
console.log(max);
console.log(max2);
Solution 19 - Javascript
const getMaxFromListByField = (list, field) => { return list[list.map(it => it[field]).indexOf(Math.max(...list.map(it => it[field])))] }