2

How can I get the highest key in an array like that:

foo[0] == undefined
foo[1] == "bar"
foo[2] == undefined
foo[3] == undefined
foo[4] == "bar"

foo.length returns me 2, so if i iterate foo.length times, I'll never get the last value.

Or is there a way to count an array considering the undefined values as well?

2
  • might be better to figure out why the holes exist and manage a clean array. Are you using delete? Instead of splice() Commented Sep 24, 2015 at 15:21
  • The error was in my code. Commented Sep 24, 2015 at 15:46

2 Answers 2

3

I am unsure why your code is not working, .length on an array like that shows 5 correctly in my example here
However, if you do not set values at all on specific indexes, you can do this :

var foo = [];
foo[1] = "bar";
foo[4] = "bar";

//grab existing indexes that have values assigned
var indexes = foo.map(function(val, idx) { return idx; });
//get the last one, this + 1 is your real length
var realLength = indexes[indexes.length - 1] + 1;
console.log("Real length: ", realLength);
//iterate using for loop
for(var i=0; i<realLength; i++) {
    var val = foo[i];
    console.log(i, val);
}
Sign up to request clarification or add additional context in comments.

7 Comments

OP not trying to assign the values...is showing holes in array. That's why length is 2
I'm not using == to assign, I just gave an example that the value is equal (==) to. (comparing)
that's fair enough :)
try to just initialize the ones that have a value
Ah ok. Well this is understandable. According to ES5 array is essentially an Object with indexes implemented as integer properties. And as thus if you do not set a value on a specific index, this property does not exist, and so won't be iterated on.
|
1

Highest Key

var index = foo.lastIndexOf(foo.slice(-1)[0]);

Comments

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.