从JavaScript中的数组获取最大n个值
我们需要编写一个JavaScript函数,该函数将Numbers数组作为第一个参数,并将数字(例如n)作为第二个参数。
然后,我们的函数应该从数组中选择n个最大的数字,并返回一个由这些数字组成的新数组。
示例
为此的代码将是-
const arr = [3, 4, 12, 1, 0, 5, 22, 20, 18, 30, 52];
const pickGreatest = (arr = [], num = 1) => {
if(num > arr.length){
return [];
};
const sorter = (a, b) => b - a;
const descendingCopy = arr.slice().sort(sorter);
return descendingCopy.splice(0, num);
};
console.log(pickGreatest(arr, 3));
console.log(pickGreatest(arr, 4));
console.log(pickGreatest(arr, 5));输出结果
控制台中的输出将是-
[ 52, 30, 22 ] [ 52, 30, 22, 20 ] [ 52, 30, 22, 20, 18 ]
热门推荐
6 保研的祝福语简短
10 年轻20岁祝福语简短
11 朋友结婚祝福语信息简短
12 女孩婚礼贺卡祝福语简短
13 30段点歌简短祝福语
14 虎年春节祝福语图文简短
15 写给后妈祝福语大全简短
16 简短回复生日祝福语
17 校长送毕业祝福语简短
18 毕业立体贺卡祝福语简短