最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

typescript - Javascript - Get max number from list of objects, each with a property that is a number - Stack Overflow

programmeradmin0浏览0评论

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
Add a ment  | 

4 Answers 4

Reset to default 7
const 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
发布评论

评论列表(0)

  1. 暂无评论