Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using an integer as a key in an associative array in JavaScript

People also ask

Can you use integers as keys in JavaScript?

As an alternative to string keys you can use integer keys but if you do use a string key you cannot refer to the value using its ordinal position in the array. For example if you define the array as: array={'key1': 'value1', 'key2': 'value2'};

Can an array be a key in JavaScript?

On each iteration, we assign the array value as a key in the object and return the new value of the accumulator variable. We initialized each key to an empty string, however you can assign whatever value suits your use case. The object will contain all of the array's elements as keys after the last iteration.

Can we get key from value in JavaScript?

To get an object's key by it's value:keys() method to get an array of the object's keys. Use the find() method to find the key that corresponds to the value. The find method will return the first key that satisfies the condition.

Can you index an integer in JavaScript?

Yes, technically array-indexes are strings, but as Flanagan elegantly put it in his 'Definitive guide': "It is helpful to clearly distinguish an array index from an object property name. All indexes are property names, but only property names that are integers between 0 and 232-1 are indexes."


Use an object, as people are saying. However, note that you can not have integer keys. JavaScript will convert the integer to a string. The following outputs 20, not undefined:

var test = {}
test[2300] = 20;
console.log(test["2300"]);

You can just use an object:

var test = {}
test[2300] = 'Some string';

As people say, JavaScript will convert a string of number to integer, so it is not possible to use directly on an associative array, but objects will work for you in similar way I think.

You can create your object:

var object = {};

And add the values as array works:

object[1] = value;
object[2] = value;

This will give you:

{
  '1': value,
  '2': value
}

After that you can access it like an array in other languages getting the key:

for(key in object)
{
   value = object[key] ;
}

I have tested and works.


If the use case is storing data in a collection then ECMAScript 6 provides the Map type.

It's only heavier to initialize.

Here is an example:

const map = new Map();
map.set(1, "One");
map.set(2, "Two");
map.set(3, "Three");

console.log("=== With Map ===");

for (const [key, value] of map) {
    console.log(`${key}: ${value} (${typeof(key)})`);
}

console.log("=== With Object ===");

const fakeMap = {
    1: "One",
    2: "Two",
    3: "Three"
};

for (const key in fakeMap) {
    console.log(`${key}: ${fakeMap[key]} (${typeof(key)})`);
}

Result:

=== With Map ===
1: One (number)
2: Two (number)
3: Three (number)
=== With Object ===
1: One (string)
2: Two (string)
3: Three (string)

Compiling other answers:

Object

var test = {};

When using a number as a new property's key, the number turns into a string:

test[2300] = 'Some string';
console.log(test['2300']);
// Output: 'Some string'

When accessing the property's value using the same number, the number is turned into a string again:

console.log(test[2300]);
// Output: 'Some string'

When getting the keys from the object, though, they aren't going to be turned back into numbers:

for (var key in test) {
    console.log(typeof key);
}
// Output: 'string'

Map

ECMAScript 6 allows the use of the Map object (documentation, a comparison with Object). If your code is meant to be interpreted locally or the ECMAScript 6 compatibility table looks green enough for your purposes, consider using a Map:

var test = new Map();
test.set(2300, 'Some string');
console.log(test.get(2300));
// Output: 'Some string'

No type conversion is performed, for better and for worse:

console.log(test.get('2300'));
// Output: undefined
test.set('2300', 'Very different string');
console.log(test.get(2300));
// Output: 'Some string'

Use an object instead of an array. Arrays in JavaScript are not associative arrays. They are objects with magic associated with any properties whose names look like integers. That magic is not what you want if you're not using them as a traditional array-like structure.

var test = {};
test[2300] = 'some string';
console.log(test);

Try using an Object, not an Array:

var test = new Object(); test[2300] = 'Some string';