James
James

Reputation: 311

Efficient way to declare and populate multidimensional array in Javascript

What's the most efficient way to declare and populate a multidimensional array in JavaScript?

I'm currently doing this:

ff = Array();
for (i = 0; i < 30; i++) {
    ff[i] = Array();
    ff[i][i] = 1.0;
}

ff[1][2] = 0.041666667;
ff[1][3] = 0.000694444;
ff[2][3] = 0.016666667;
ff[1][4] = 0.000011574;
ff[2][4] = 0.000277778;
ff[3][4] = 0.016666667;
ff[1][5] = 0.000011574;
ff[2][5] = 0.000035315;
ff[3][5] = 0.00211888;
ff[4][5] = 0.1271328;
ff[1][6] = 0.000000025;
ff[2][6] = 0.000000589;
ff[3][6] = 0.000035315;
ff[4][6] = 0.00211888;
ff[5][6] = 0.016666667;

up to ff[n][n] where n can be up to 30, which leads to hundreds of lines of declaring array values (does this matter, even when minified?). I only need to populate the "top" half of the array since ff[n][n] = 1 and ff[i][j] = 1/(ff[j][i]) so after the declaration I loop over the whole array and invert the "top" half to populate the "bottom" half.

Upvotes: 2

Views: 3378

Answers (2)

Dancrumb
Dancrumb

Reputation: 27549

From looking at your numbers, it looks like you're trying to convert between various time units.

I wonder if a better fit wouldn't be an object.

var seconds = {
  day:   86400,
  hour:   3600,
  minute:   60,
  second:    1
};

var conversions = {};

['day','minute','hour','second'].forEach(function(fromUnit){
  var subConversions = {};
  var fromValue = seconds[fromUnit];
  ['day','minute','hour','second'].forEach(function(toUnit){
    subConversions[toUnit] = fromValue / seconds[toUnit];
  });
  conversions[fromUnit] = subConversions;
});

function convert(value, from, to){
  return value * conversions[from][to];
}

This will give you.

convert(1, 'day','hour') === 24

convert(1, 'day','second') === 86400

convert(3, 'hour','second') === 10800

Even if things are more complicated than simple time conversion, this approach is probably going to lead to much more understandable code. Once you start giving the elements of a multi-dimensional array special meanings, things can get pretty ugly.

Upvotes: 2

user1032531
user1032531

Reputation: 26281

I would do something like the following: And then I would put the script in a separate file which can be cached.

ff=[];
ff[0]=[0.041666667,000694444,016666667,000277778,016666667];
ff[1]=[0.041666667,000694444,016666667,000277778,016666667];
ff[2]=[0.041666667,000694444,016666667,000277778,016666667];
ff[3]=[0.041666667,000694444,016666667,000277778,016666667];
ff[4]=[0.041666667,000694444,016666667,000277778,016666667];
ff[5]=[0.041666667,000694444,016666667,000277778,016666667];

Upvotes: 0

Related Questions