Pierre Lechelle
Pierre Lechelle

Reputation: 302

Filling multidimensionnal array in JavaScript

I've a little problem in JavaScript.

I need to get an array width date as keys and events as values.

In PHP I would do something like this :

$var = new array();
Loop
$var[$date][] = $event;
End loop

Do you know what I mean ?

Thanks, Regards

Upvotes: 1

Views: 335

Answers (3)

Ben Lee
Ben Lee

Reputation: 53349

In javascript, you can create a data structure like that this way:

var events = {
    '2009-09-09': [],
    '2010-10-10': [],
    '2011-11-11': []
};

The events = { ... } is an object literal in javascript. Objects in javscript act very much like hashes with properties as keys, so this is essentially going to act as a hash keyed on dates. Each date is initialized with an empty array.

And you can fill it up with events like this

events[date].push(event);

If you don't know the dates ahead of time, you can dynamically fill the hash. So, you'd start with just an empty hash:

var events = {};

Then you'd check for the date key every time you go to add an event, like this:

if (!(date in events)) events[date] = [];
events[date].push(event);

The date in events checks to see if the key exists, and the ! negates it. So if the date key does not exist, it initializes the date key with an empty array. Then it pushes the event for that date as normal.

Upvotes: 3

6502
6502

Reputation: 114579

To add an element to a list you can use the push javascript method of array objects...

events_by_date = {};
...
for (var i=0; i<events.length; i++) {
    if (!events_by_date[events[i].date]) {
        // This is the first event on this date
        // so create the list
        events_by_date[events[i].date] = [];
    }
    // Add the event to the list of events in that date
    events_by_date[events[i].date].push(events[i]);
}

Upvotes: 1

Dave
Dave

Reputation: 11899

In Javascript key-value mappings are handled by Objects. An empty object is just {}. You can do this sort of thing like (note that var is a reserved word in Javascript so I can't copy your example exactly):

var variable = {};
var date_list = [1,2,3];
var event_list = [4,5,6];
for (i in date_list){
    var key = date_list[i];
    var value = event_list[i];
    variable[key] = value;
}

// variable now contains: {1:4, 2:5, 3:6}

console.log(variable[1]);
// prints 4

EDIT: That's the basic syntax. If you want to have an array for each key, just do something like that but with arrays instead of numbers in event_list. For example:

my_dates = {'2011': [1,2,3], '2010': [6,7,8]}

Upvotes: 1

Related Questions