最新消息:Welcome to the puzzle paradise for programmers! Here, a well-designed puzzle awaits you. From code logic puzzles to algorithmic challenges, each level is closely centered on the programmer's expertise and skills. Whether you're a novice programmer or an experienced tech guru, you'll find your own challenges on this site. In the process of solving puzzles, you can not only exercise your thinking skills, but also deepen your understanding and application of programming knowledge. Come to start this puzzle journey full of wisdom and challenges, with many programmers to compete with each other and show your programming wisdom! Translated with DeepL.com (free version)

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

matteradmin9PV0评论

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

Articles related to this article

Post a comment

comment list (0)

  1. No comments so far