Reputation: 4169
Maybe I'm not putting in the correct search terms, because I can't find what I want, but I'd like to do something like the below in javascript. I believe the issue could be that I'm trying to dynamically create and assign a value to an array in one call which might not be allowed, or maybe my syntax is just wrong (I come from a PHP background).
var array = [];
array[key][] = value;
return array;
I'm looping through an existing array, and every time I come across a key, I want to add its associated value to a new array under that key. If array[key]
doesn't exist yet I want it to be created. If it already exists I want a new value to be added to the existing array[key]
. I would like the end result to look something like this:
array = [
[key1] = [value1, value2, value3, value4],
[key2] = [value1, value2, value3, value4],
...
]
It doesn't have to be an array. It can be an object.
Upvotes: 0
Views: 786
Reputation: 8878
You can use Array to do it, but it looks like Map is what you are looking for? The keys can be stored as Map's key, while for map's object, you can store the Array Objects.
Check out this link Javascripy Map Object
Upvotes: 0
Reputation: 529
Demo code as below:
var array = [];
function pushToArray(key, value){
var subArray = array[key];
if( typeof subArray == "undefined"){
subArray = [];
array[key] = subArray;
}
subArray.push(value);
return subArray;
}
pushToArray("key1", "value11");
pushToArray("key1", "value12");
pushToArray("key2", "value21");
pushToArray("key2", "value22");
console.log(array);
Upvotes: 1