It seems to me that one of the big downsides of javascript is that there are no associative arrays. Objects don't provide order, arrays don't provide keys.
There is also the possibility of arrays containing objects:
[{key1:value1}, {key2:value2}]
But as far as I know, there is no easy way to access elements by keys in this approach (without having to iterate through all elements).
That's why I started to think about the following approach, that is making an array associative by adding a element mapper:
Array.prototype.addKeyToLastElement = function(key) {
if (!this.elementMapper) this.elementMapper = {};
this.elementMapper[key] = this.length-1;
}
Array.prototype.getElementByKey = function(key) {
if (this.elementMapper && this.elementMapper[key] !== undefined) {
return this[this.elementMapper[key]];
}
else {
return undefined;
}
}
var test = [];
test.push(1);
test.addKeyToLastElement('a');
test.push(3);
test.addKeyToLastElement('b');
// get element by key
console.log(test.getElementByKey("a"));
I know that this is far from perfect, it's just a first try to see if it works. I was just wondering why I couldn't find any similar solutions.
Is this approach deprecated? If yes, what are the best alternatives?
My minimal requirements are:
- Access elements by keys (retrieve/ alter value)
- Maintain the elements order
- Sort elements both by key and value