I have a list of objects, every object has the time
property which is a integer (the code is actually typescript, so time
is actually of type number
).
I want to get the highest value of time
amongst the objects in the list.
What is a concise, but understandable, way to do this? My current approach is the following, but it seems clunky:
let times = []
for(let adventurer of adventurers) {
times.push(adventurer.time)
}
Math.max(...times)
I have a list of objects, every object has the time
property which is a integer (the code is actually typescript, so time
is actually of type number
).
I want to get the highest value of time
amongst the objects in the list.
What is a concise, but understandable, way to do this? My current approach is the following, but it seems clunky:
let times = []
for(let adventurer of adventurers) {
times.push(adventurer.time)
}
Math.max(...times)
Share
Improve this question
edited Aug 16, 2018 at 3:27
Foobar
asked Aug 16, 2018 at 3:22
FoobarFoobar
8,54521 gold badges101 silver badges183 bronze badges
4 Answers
Reset to default 7const maxVal = Math.max(...adventurers.map(o => o.time))
const maxTime = adventurers
.reduce((currentMax, { time }) => Math.max(currentMax, time), 0);
I'm not sure if this is valid syntax, but you could try:
function getMax(array) {
let max = 0;
for (let item in array) {
if (max < item ) max = item;
else continue;
}
return max;
}
Also, if you're dealing with time or another data model you may have to customize the sort.
This is javascript:
array.sort(function pare(a, b) {
if (a is less than b by some ordering criterion) {
return -1;
}
if (a is greater than b by the ordering criterion) {
return 1;
}
// a must be equal to b
return 0;
});
Try this
var adventurers = [
{time : 100},
{time : 120},
{time : 160},
{time : 90},
{time : 200},
]
const maxTime = adventurers.sort((val1,val2)=> {
return (val1.time < val2.time ) ? 1 : -1
})[0]
console.log(maxTime) // {time : 200}
console.log(maxTime.time) // 200