如何从js中的数组中获取最小的两个数字? [英] How can I get the smallest two numbers from an array in js?

查看:446
本文介绍了如何从js中的数组中获取最小的两个数字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嘿我一直试图从数组中返回2个最小的数字,无论索引如何。你能帮帮我吗?

解决方案


  • 按升序对数组排序。

  • 使用 Array#slice 获取前两个元素(最小的元素)。



< pre class =snippet-code-js lang-js prettyprint-override> var arr = [5,4,7,2,10,1],res = arr.sort((a,b) )=> a - b).slice(0,2); console.log(res);


Hey I've been trying to return the 2 smallest numbers from an array, regardless of the index. Can you please help me out?

解决方案

  • Sort the array in the ascending order.
  • Use Array#slice to get the first two elements (the smallest ones).

var arr = [5, 4, 7, 2, 10, 1],
    res = arr.sort((a,b) => a - b).slice(0, 2);
    console.log(res);

这篇关于如何从js中的数组中获取最小的两个数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆