簡體   English   中英

在對象數組中查找最小值並返回其他屬性的最佳方法?

[英]Best way to find min value in array of objects and also return the other property?

我有一個students對象,我想獲得最小的學生的名字。

const students = [
  { name: 'Hans', age: 3 },
  { name: 'Ani', age: 7 },
  { name: 'Budi', age: 10 },
  { name: 'Lee', age: 13 }
 ]

這樣我最小的年齡

function getYoungestAge(data) {
   return resultMin = data.reduce((min, p) => p.age < min ? p.age : min, data[0].age)
}

getYoungestAge(students) // return 3

我如何不僅可以返回年齡,還可以返回姓名? // example: 3 and Hans

您總是可以通過reduce來獲取整個對象,而不僅僅是年齡

 const students = [ { name: 'Hans', age: 3 }, { name: 'Ani', age: 7 }, { name: 'Budi', age: 10 }, { name: 'Lee', age: 13 } ] function getYoungestAge(data) { return data.reduce((min, p) => p.age < min.age ? p : min, data[0]) } var youngest = getYoungestAge(students) console.log(youngest); 

另一種方法是對列表進行排序並排在第一位。 注意:這種方式更改原始數組。 在某些情況下這很好,而在另一些情況下則是不希望的。 在大多數情況下,我更喜歡上面的第一種方式。

 const students = [ { name: 'Hans', age: 3 }, { name: 'Ani', age: 7 }, { name: 'Budi', age: 10 }, { name: 'Lee', age: 13 } ] function getYoungestAge(data) { data.sort( (x,y) => x.age-y.age); return data[0]; } var youngest = getYoungestAge(students) console.log(youngest); 

還要注意, 這兩個解決方案都返回年齡最低的第一項,其中有1個以上的學生具有相同的年齡。

您可以返回包含過濾對象的數組。 這是一個循環,如果某些人的最小年齡相同,則將返回該年齡的所有人。

 function getYoungestAge(data) { return data.reduce(function (r, o, i) { if (!i || o.age < r[0].age) { return [o]; } if (o.age === r[0].age) { r.push(o) } return r; }, []); } const students = [{ name: 'Hans', age: 3 }, { name: 'Ani', age: 7 }, { name: 'Budi', age: 10 }, { name: 'Lee', age: 13 }] console.log(getYoungestAge(students)); 

將數組簡化為Map ,以年齡為key ,並將值設為所有具有該年齡的學生的數組。 要使年齡最小,請找到地圖上的鍵的最小值 ,然后從地圖上獲取該鍵的值:

 const students = [{"name":"Hans","age":3},{"name":"Ani","age":7},{"name":"Morgan","age":3},{"name":"Budi","age":10},{"name":"Lee","age":13}] const studentsByAgeMap = students.reduce((m, o) => { m.has(o.age) || m.set(o.age, []) m.get(o.age).push(o) return m }, new Map()) const result = studentsByAgeMap.get(Math.min(...studentsByAgeMap.keys())) console.log(result) 

使用Lodash,可以在一行中完成上述操作。

_.minBy(學生,函數(o){return o.age})

暫無
暫無

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

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