如何从javascript中的数组中获取第二大元素 [英] How do I get the second largest element from an array in javascript

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

问题描述

我有一个像这样的整数数组:

I have an integer array like this :

arr[20,120,111,215,54,78];

我需要一个以数组为参数并返回该数组第二大元素的函数.

I need a function taking an array as its argument and returning the second largest element of that array.

推荐答案

var secondMax = function (){ 
    var arr = [20, 120, 111, 215, 54, 78]; // use int arrays
    var max = Math.max.apply(null, arr); // get the max of the array
    arr.splice(arr.indexOf(max), 1); // remove max from the array
    return Math.max.apply(null, arr); // get the 2nd max
};

演示

更新

davin 所指出的,可以通过不进行剪接而是通过临时 -Infininty 替换最大值来增强性能:

As pointed out by davin the performance could be enhanced by not doing a splice but temporarily replacing the max value with -Infininty:

var secondMax = function (arr){ 
    var max = Math.max.apply(null, arr), // get the max of the array
        maxi = arr.indexOf(max);
    arr[maxi] = -Infinity; // replace max in the array with -infinity
    var secondMax = Math.max.apply(null, arr); // get the new max 
    arr[maxi] = max;
    return secondMax;
};

无论如何,恕我直言,最好的算法是杰克算法.1次通过,转换为数字.我的很短,使用内置方法,只想提供它作为替代方案,以展示实现目标的所有不同方式.

Anyway, IMHO the best algorithm is Jack's. 1 pass, with conversion to number. Mine is just short, using builtin methods and only wanted to provide it as an alternative, to show off all the different ways you can achieve the goal.

这篇关于如何从javascript中的数组中获取第二大元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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