简体   繁体   English

如何从 javascript 中的数组中获取第二大元素

[英]How do I get the second largest element from an array in javascript

I have an integer array like this:我有一个像这样的 integer 数组:

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.我需要一个 function 以数组作为参数并返回该数组的第二大元素。

The most straightforward implementation, without modifying the original array, is to iterate and track the biggest and next biggest:最直接的实现,不修改原数组,就是迭代跟踪最大和次大:

 function nextBiggest(arr) { let max = -Infinity, result = -Infinity; for (const value of arr) { const nr = Number(value) if (nr > max) { [result, max] = [max, nr] // save previous max } else if (nr < max && nr > result) { result = nr; // new second biggest } } return result; } const arr = ['20','120','111','215','54','78']; console.log(nextBiggest(arr));

Original answer原答案

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
};

demo演示

Update 1更新 1

As pointed out by davin the performance could be enhanced by not doing a splice but temporarily replacing the max value with -Infininty :正如davin所指出的,可以通过不进行拼接而是暂时-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;
};

Anyway, IMHO the best algorithm is Jack's.无论如何,恕我直言,最好的算法是杰克的。 1 pass, with conversion to number. 1 次通过,转换为数字。 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.我的很短,使用内置方法,只想提供它作为替代方案,以炫耀您可以实现目标的所有不同方法。

Update 2更新 2

Edge case with multiple values.具有多个值的边缘情况。

As comments pointed it out: this solution "does not work" if we have an array like [3, 3, 5, 5, 5, 4, 4] .正如评论指出的那样:如果我们有一个像[3, 3, 5, 5, 5, 4, 4]这样的数组,这个解决方案“不起作用”。 On the other hand it would be also a matter of interpretation what we would consider "the 2nd largest element".另一方面,我们认为“第二大元素”也是一个解释问题。 In the example we have:在示例中,我们有:

  1. 3 elements with the largest value (5) at indices: 2,3,4在索引处具有最大值 (5) 的 3 个元素:2,3,4
  2. 2 elements with the second largest value (4) at indices: 5,6 2 个在索引处具有第二大值 (4) 的元素:5,6
  3. 2 elements with the second smallest value (3) at indices: 1,2在索引处具有第二个最小值 (3) 的 2 个元素:1,2

The 2nd largest element could be interpreted as:第二大元素可以解释为:

  1. the 2nd (largest element) - 5 at index 3 - assuming that there is an order, and that we aim for a unique value第二个(最大的元素) - 索引 3 处的 5 - 假设有一个订单,并且我们的目标是一个唯一的值
  2. the (2nd largest) element - 4 at index 5 - assuming that there is an order, and that we aim for a unique value (第二大)元素 - 索引 5 处的 4 - 假设有一个订单,并且我们的目标是唯一值

The simplest solution is to sort :最简单的解决方案是排序:

// here's your array :
var stringArray = new Array('20','120','111','215','54','78');

// let's convert it to a real array of numbers, not of strings :
var intArray = stringArray.map(Number);

// now let's sort it and take the second element :
var second = intArray.sort(function(a,b){return b-a})[1]; 

If you don't want the simplest but the fastest (you probably don't need it), then you'd have to write your for loop and store the two greatest elements while looping.如果您不想要最简单但最快的(您可能不需要它),那么您必须编写for循环并在循环时存储两个最大的元素。

First sort it backwards and then get the second element:首先向后排序,然后获取第二个元素:

['20','120','111','215','54','78'].sort(function(a, b) { return b - a; })[1];
// '120'

Obviously works with strings too.显然也适用于字符串。

Sort the array and then return the second index.对数组进行排序,然后返回第二个索引。

var arr = ['20','120','111','215','54','78'];

arr.sort(function(a,b){
    return b-a;
});

console.log(arr[1]);

Sort your array from smallest to largest, then grab second one from the end with .length-2将您的数组从小到大排序,然后用.length-2从末尾抓取第二个数组

var myArray =['20','120','111','215','54','78'];
var secondLargest = myArray.sort(function(a,b){return a - b})[myArray.length-2];
alert(secondLargest); //120;

You can try this:你可以试试这个:

function second_highest(arr)
{
  var second_highest = arr.sort(function(a, b) { return b - a; })[1];
  return second_highest;

}
const arr = [20, 120, 111, 215, 54, 78];

console.log(arr.sort((i, j) => (i < j? +1: i > j? -1: 0))[1]); console.log(arr.sort((i, j) => (i < j?+1: i > j?-1: 0))[1]);

const ages = [40, 100, 1, 5, 25, 10]; ages.sort((a, b) => b - a);

function getSecondLargest(nums) {
 return [...new Set(nums)].sort((a,b)=>b-a)[1]    
}

what if the array of numbers is something like this:如果数字数组是这样的怎么办:

let arr = [6, 5, 4, 6, 3]

it is obvious that getting the second wont work.很明显,获得第二个是行不通的。 so what else could be done here?那么这里还能做什么呢?

my suggestion is:我的建议是:

function getSecondLargest(nums) {
    nums.sort((a, b) => b - a);
    let secondBiggest = nums.find(element => element < nums[0]);
    return secondBiggest; // will return 5

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM