Reputation: 23
I have an array with a few nums:
var arr = ["10","14","23","2","21","17","72","16","73","52"];
I know I can use Math.min.apply(Math, arr)
to get from an array the lowest number or use Math.max.apply(Math,arr)
for the maximum number, but now I want only the minimum or maximum number from the last 3 elements in the array.
Any suggestions how I could do this?
Upvotes: 0
Views: 1693
Reputation: 48600
Using Array.prototype.slice()
, you can extract a range of values within an array. This will allow you to only perform the min()
and max()
function on the values within the designated range.
The minmax()
function below will return an object with min
and max
values.
function minmax(arr, begin, end) {
arr = [].slice.apply(arr, [].slice.call(arguments, 1));
return {
'min' : Math.min.apply(Math, arr),
'max' : Math.max.apply(Math, arr)
}
}
var values = ["10","14","23","2","21","17","72","16","73","52"];
var result = minmax(values, -3);
document.body.innerHTML = JSON.stringify(result, undefined, ' ');
body {
font-family: monospace;
white-space: pre;
}
Upvotes: 2