获取数组中指定个数的最大元素

语法

  1. import { maxArray } from 'warbler-js'
  2. const result = maxArray(arr, n)

参数

  • arr (Array) : 需要获取最大元素的数组 。
  • n (Number) : 需要获取最大元素的数量 。

返回值

Array : 指定数量的最大元素组成的数组。

源码

  1. const maxArray = (arr, n = 1) => [...arr].sort((a, b) => b - a).slice(0, n);

例子

  1. import { maxArray } from 'warbler-js'
  2. const ages = [10, 2, 5, 8, 100, 500, 3, 30, 9];
  3. const result1 = maxArray(ages)
  4. const result2 = maxArray(ages,3)
  5. console.log(result1) //=> [500]
  6. console.log(result2) //=> [500, 100, 30]