1

I have simple question. I have JS array like that:

data[-5]=[...];
data[-2]=[...];
data[-1]=[...];
data[4]=[...];
data[6]=[...];
data[7]=[...];

How can I get automatically the minimum (data[-5]) and maximum (data[7]) element?

asked Feb 13, 2015 at 15:04
5
  • 5
    Negative indexes to arrays are improper in JavaScript. They'll work, sort-of, but if you do something like serialize the array with JSON.stringify you'll lose those, and they won't be reflected in the array length. Commented Feb 13, 2015 at 15:07
  • Why would you ever have a negative index?? Commented Feb 13, 2015 at 15:08
  • 1
    @Pointy: I haven't heard of any language whose arrays could be indexed with negative values... Commented Feb 13, 2015 at 15:10
  • @Bergi I think you could/can do it in Pascal :) Commented Feb 13, 2015 at 15:12
  • @Bergi VB also supports them. Commented Feb 13, 2015 at 15:24

2 Answers 2

5

Negative indexes are not actual indexes. They won't work all time. They are like just as any other property of an object.

However, you could do what you want by iterating through the enumerable properties(Which is bad for an array, but nevertheless) and adding number properties to an Array.

var idxs = Object.keys(arr).filter(isFinite); // just take the Number properties
var min = Math.min.apply(Math, idxs),
 max = Math.max.apply(Math, idxs);
answered Feb 13, 2015 at 15:12
Sign up to request clarification or add additional context in comments.

Comments

2

Short with no loops:

var keys = Object.keys(data);
var sorted = keys.sort(function(a, b){return a-b});
var min = data[sorted[0]];
var max = data[sorted[sorted.length-1]];
answered Feb 13, 2015 at 15:17

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.