maxBy
找到数组中通过将 getValue 函数应用于每个元素来返回具有最大值的元素,并返回该元素的值。如果数组为空,则返回 null。
函数接受一个数组和一个函数作为参数,返回数组中通过将 getValue 函数应用于每个元素来返回具有最大值的元素,并返回该元素的值。如果数组为空,则返回 null。
签名
ts
function maxBy<T>(arr : T[], getValue : (item : T) => number) : T | null参数
arr(T[]):需要查找的数组。getValue((item : T) => number):一个函数,用于从数组的每个元素中提取一个值,用于比较大小。
返回值
T | null:返回数组中通过将 getValue 函数应用于每个元素来返回具有最大值的元素,并返回该元素的值。如果数组为空,则返回 null。
示例
ts
import { maxBy } from '@/uni_modules/kux-toolkit'
const arr16 = [
{ id: 1 },
{ id: 2 },
{ id: 3 },
]
const maxItem = maxBy(arr16, (item) : number => item['id'] as number)
console.log(maxItem) // { id: 3 }