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?

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.
    – Pointy
    Commented Feb 13, 2015 at 15:07
  • Why would you ever have a negative index??
    – Dean.DePue
    Commented Feb 13, 2015 at 15:08
  • 1
    @Pointy: I haven't heard of any language whose arrays could be indexed with negative values…
    – Bergi
    Commented Feb 13, 2015 at 15:10
  • @Bergi I think you could/can do it in Pascal :)
    – Pointy
    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);
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]];

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.