How to create an array in JavaScript whose indexing starts at 1?

Since this question also pops up for a Google search like "javascript start array at 1" I will give a different answer:

Arrays can be sliced. So you can get a sliced version of the Array like this:

var someArray = [0, 1, 2, 3];

someArray.slice(1);
[1, 2, 3]

someArray.slice(2, 4);
[2, 3]

Source: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/slice


It isn't trivial. It's impossible. The best you could do is create an object using numeric properties starting at 1 but that's not the same thing.

Why exactly do you want it to start at 1? Either:

  • Start at 0 and adjust your indices as necessary; or

  • Start at 0 and just ignore index 0 (ie only use indices 1 and up).


A simple solution is to fill the zeroth item:

var map = [null, 'January', 'February', 'March'];
'First month : ' + map[1];


Semantically it would be better to use an object:

var map = {1:'January', 2:'February', 3:'March'};
'First month : ' + map[1];

Note these keys are not ints actually, object keys are always strings.
Also, we can't use dot notation for accessing. (MDN - Property Accessors)


I'd choose the first solution, which I think is less confusing.


You could use delete to remove the first element like so:

let arr = ['a','b','c'];
delete arr[0];

console.log(arr[0]);
console.log(arr[1]);

Or just not define it at all:

let arr = [,'b','c'];

console.log(arr[0]);
console.log(arr[1]);

If you want to make sure that you always get the first truthy element regardless of the index and have access to ES6 you can use:

arr.find(Boolean)