how to get second largest number from array in javascript
How to get second largest number from array in javascript.
we have solved this question in our collages but in C.
Logics are always same but method of write about a solution in different language are different .
i know javascript that why i am wrinting this code in javascript .
so what we have done here .we just take array with non-ascending order value .we dont know which key has largest value .
we use Math.max function of javascript to get largest number .
we are saying that this is only logic to find largest value in array.we Found it easy that 's why we are explain with this example with the help of apply method.
The apply() method calls a function with a given this value and arguments provided as an array (or an array-like object).
after that we have used a each loop to find index number of largest number then slice it from array.
again find largest number in array we got that .
Below 's code .paste this code in any script tag get result.
var myfun = function IInd() {
var a = [12, 45, 3, 65, 11];
var index = 0;
var maxNUm = Math.max.apply(null, a);
console.log(maxNUm);
$.each(a, function (i, v) {
console.log(v)
if (v == maxNUm) {
index = i;
}
});
a.splice(index, 1);
console.log(a);
var IImax = Math.max.apply(null, a);
console.log(IImax);
return IImax;
}
console.log("second largest num",myfun());
we have solved this question in our collages but in C.
Logics are always same but method of write about a solution in different language are different .
i know javascript that why i am wrinting this code in javascript .
so what we have done here .we just take array with non-ascending order value .we dont know which key has largest value .
we use Math.max function of javascript to get largest number .
we are saying that this is only logic to find largest value in array.we Found it easy that 's why we are explain with this example with the help of apply method.
The apply() method calls a function with a given this value and arguments provided as an array (or an array-like object).
after that we have used a each loop to find index number of largest number then slice it from array.
again find largest number in array we got that .
Below 's code .paste this code in any script tag get result.
var myfun = function IInd() {
var a = [12, 45, 3, 65, 11];
var index = 0;
var maxNUm = Math.max.apply(null, a);
console.log(maxNUm);
$.each(a, function (i, v) {
console.log(v)
if (v == maxNUm) {
index = i;
}
});
a.splice(index, 1);
console.log(a);
var IImax = Math.max.apply(null, a);
console.log(IImax);
return IImax;
}
console.log("second largest num",myfun());
No comments: