-
Notifications
You must be signed in to change notification settings - Fork 1
/
arrays.js
42 lines (40 loc) · 1.2 KB
/
arrays.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
/**
* Return the second largest number in the array.
* @param {Number[]} nums - An array of numbers.
* @return {Number} The second largest number in the array.
**/
function getSecondLargest(nums) {
// Complete the function
let sorted = nums.sort(function (a, b) {return a - b;});
let _sorted = sorted.filter(function (value, index, array) {
return index === array.indexOf(value);
});
return _sorted[_sorted.length - 2];
}
// while loop
function getSecondLargest(nums) {
// getting the maximum value
let max = Math.max.apply(null, nums);
let maxI = nums.indexOf(max);
nums[maxI] = -Infinity;
// returning the second maximum value (if the maximum is duplicated)
while(max == Math.max.apply(null, nums)) {
let max = Math.max.apply(null, nums);
let maxI = nums.indexOf(max);
nums[maxI] = -Infinity;
}
return Math.max.apply(null, nums);
}
//for loop
function getSecondLargest(nums) {
let max = Math.max.apply(null, nums);
let secondLargestNum;
let removeLargestNum = [];
for (let i = 0; i < nums.length; i++) {
if (nums[i] !== max) {
removeLargestNum.push(nums[i]);
}
}
secondLargestNum = Math.max.apply(null, removeLargestNum);
return secondLargestNum;
}