簡體   English   中英

Javascript-從對象列表中獲取最大數量,每個對象的屬性均為數字

[英]Javascript - Get max number from list of objects, each with a property that is a number

我有一個對象列表,每個對象都有一個time屬性,它是一個整數(代碼實際上是打字稿,所以time實際上是number類型)。

我想在列表中的對象中獲得最高的time值。

什么是簡潔但可以理解的方法? 我當前的方法如下,但似乎很笨拙:

let times = []

for(let adventurer of adventurers) {
    times.push(adventurer.time)
}

Math.max(...times)
const maxVal = Math.max(...adventurers.map(o => o.time))
const maxTime = adventurers
    .reduce((currentMax, { time }) => Math.max(currentMax, time), 0);

我不確定這是否是有效的語法,但是您可以嘗試:

function getMax(array) {
let max = 0;
for (let item in array) {
    if (max < item ) max = item;
    else continue;
}
return max;

}

另外,如果您要處理時間或其他數據模型,則可能必須自定義排序。

這是javascript:

    array.sort(function compare(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;
});

嘗試這個

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM