查找数组中的第二大数字 [英] Find the second largest number in array
本文介绍了查找数组中的第二大数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个由[31,23,12]之类的三个元素组成的数组,我想找到第二大元素及其相关位置而无需重新排列该数组.
I have an array of three element like [31,23,12] and I want to find the second largest element and its related position without rearranging the array.
示例:
array = [21,23,34]
Second_largest = 23;
Second_largest = 23;
位置= 1;
推荐答案
使用.slice(0)
复制原始数组的克隆,例如:
Make a clone of your original array using .slice(0)
like :
var temp_arr = arr.slice(0);
然后对其进行存储,以便在数组的索引temp_arr.length - 2
中获得第二个最大值:
Then sor it so you get the second largest value at the index temp_arr.length - 2
of your array :
temp_arr.sort()[temp_arr.length - 2]
现在,您可以使用indexOf()
函数来获取该值的索引,如:
Now you could use indexOf()
function to get the index of this value retrieved like :
arr.indexOf(second_largest_value);
var arr = [23, 21, 34, 34];
var temp_arr = [...new Set(arr)].slice(0); //clone array
var second_largest_value = temp_arr.sort()[temp_arr.length - 2];
var index_of_largest_value = arr.indexOf(second_largest_value);
console.log(second_largest_value);
console.log(index_of_largest_value);
这篇关于查找数组中的第二大数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文