0

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?

7
  • "last 3 characters" or last 3 elements? Commented Mar 19, 2015 at 10:46
  • can you use this arr.slice(Math.max(arr.length - 3, 1)) and then apply the Math functions to the output array? Commented Mar 19, 2015 at 10:48
  • @Vohuman, the last 3 elements. Changed it in the description. Commented Mar 19, 2015 at 10:49
  • Yes, you can use Array.prototype.slice for slicing the array, then you can use the sliced array. var slicedArr = arr.slice(-3) Commented Mar 19, 2015 at 10:50
  • @Vohuman : you clearly haven't read it. I want from the last 3 elements, the highest or lowest number. I don't wanna slice anything ;/ Commented Mar 19, 2015 at 10:52

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

1 Comment

That's an advanced solution. Nice approach!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.