Rafael
Rafael

Reputation: 634

Get highest index key of Javascript array

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?

Upvotes: 2

Views: 3559

Answers (2)

Daniel Gruszczyk
Daniel Gruszczyk

Reputation: 5612

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

Upvotes: 3

BenG
BenG

Reputation: 15154

Highest Key

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

Upvotes: 1

Related Questions