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

语法

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

参数

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

返回值

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

源码

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

例子

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