Efficient way to declare and populate multidimensional array in Javascript - 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.

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.

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];

Related

How to write a function, which creates an array of objects of certain length? Object has custom generated data

I have an object with randomly generated data:
var obj = {
price: getRandomNumberRange(10, 200),
rooms: getRandomNumberRange(1, 5)
};
where
var getRandomNumberRange = function (min, max) {
return Math.floor(Math.random() * (max - min) + min);
};
I keep trying and failing to write a function, which will allow to create an array of 4 objects, so each objects' data will be regenerated at the time of creation. My function:
var createArr = function () {
var arr = [];
for (var i = 0; i < 5; i++) {
arr.push(obj);
}
return arr;
};
In other words I expect to get this kind of array:
var arr = [{price:40, rooms:2}, {price:23, rooms:4}, {price:99, rooms:2}, {price:191, rooms:3}];
But I keep getting this:
var arr = [{price:40, rooms:2}, {price:40, rooms:2}, {price:40, rooms:2}, {price:40, rooms:2}];
Will appreciate your help!
UPD. Thanks to everyone who suggested more complex way to solve my problem. As soon as I progress in JS I will recheck this thread again!
It looks like you reuse the object for pushing over and over and because of the same object, it pushes the same object reference with the latest values.
To overcome this, you need to create a new object for each loop and assign the random values with short hand properties.
// inside the loop
let price = getRandomNumberRange(10, 200),
rooms = getRandomNumberRange(1, 5);
array.push({ price, rooms }); // short hand properties

Create dynamic variable names and values using for loop: JavaScript

I have a list of values that I want to dynamically assign to another list of values:
var activeMachines = [41,44,46]
for(i = 0; i < activeMachines.length; i++){
var temp + activeMachines[i] = document.getElementById("tempData"+activeMachines[i]);
var humid + activeMachines[i] = document.getElementById("humidData"+activeMachines[i]);
var time + activeMachines[i] = document.getElementById("timeData"+activeMachines[i]);
}
What I am hoping to achieve is that this loop would create 6 new variables in total:
temp41 = document.getElementById("tempData41");
temp44 = document.getElementById("tempData44");
...
Above is not working. I have read some other posts suggesting using arrays, but I think I need to somehow dynamically create a dictionary, and I can't seem to get the syntax right to achieve this. any suggestions?
Anytime you're struggling to dynamically define variable names it's an indication that you should step back and reconsider your data structures. It's almost always the wrong choice that leads to difficult, messy code.
In this case it looks like you have three things that have an id and a temp, humidity and time property. This is exactly what objects are for.
For example you might represent the data like:
let data = { machine_41: {temp: 40, humid: 10, time: 200},
machine_44: {temp: 30, humid: 15, time: 500},
} // etc
Now all your data is in one place and you can access it with simple properties:
data.machine_41.temp
To go from your array of numbers to this object is simple with reduce():
var activeMachines = [41,44,46]
let data = activeMachines.reduce((obj, machineID) => {
// some fake data
temp = 20 // or document.getElementById etc..
humidity = 10
time = 600
obj['machine_'+machineID] = {temp, humidity, time}
return obj
}, {})
console.log("machine_41 humidity:",data.machine_41.humidity)
console.log(data)
This might not be the exact data structure you need (maybe it's better as an array for example), but this approach will serve you better than trying to create a bunch of individual variables.
You can use the window object for doing that, however, I recommend you to create your own object to store those "variables" as properties within that new key-value object.
var activeMachines = [41,44,46]
var obj = {};
for(i = 0; i < activeMachines.length; i++){
obj['temp' + activeMachines[i]] = document.getElementById("tempData"+activeMachines[i]);
obj['humid' + activeMachines[i]] = document.getElementById("humidData"+activeMachines[i]);
obj['time' + activeMachines[i]] = document.getElementById("timeData"+activeMachines[i]);
}
Try this
var activeMachines = [41,44,46];
var output = {};
for(i = 0; i < activeMachines.length; i++){
output["temp" + activeMachines[i]] = document.getElementById("tempData"+activeMachines[i]);
output["humid" + activeMachines[i]] = document.getElementById("humidData"+activeMachines[i]);
output["time" + activeMachines[i]] = document.getElementById("timeData"+activeMachines[i]);
}
console.log(output);
All your variables are define in this variable.
Access like output['temp41']
You can use an object and create properties instead of variables.
var context = {};
for (i = 0; i < activeMachines.length; i++) {
context[`temp${activeMachines[i]}`] = document.getElementById("tempData"+activeMachines[i]);
}
And the access those data with context.temp41 or context["temp41"]

how much time a look up take in an object?

I have an object,
obj = {};
now I am adding items into this object as,
obj[element] = /*something*/
now if I want to access this object for key = element as,
obj[element];
what would be time complexity of this operation.
And please dont suggest using of Array instead of Object, I know array has constant time look up because I am adding elements at random numbers (using them as index), so if Ii use array, I will have a sparse array and that would be inefficient in terms of memory.
It is minimal enough for you to not worry about it. Objects are a core part of javascript, and micro-optimization is bad.
You're much better off writing understandable code (whether it's with objects or what-not) than writing code that saves you 0.000000000001 seconds.
Just you need to know: Array is an Object too in JavaScript.
Also to check speed of any operation you can do something like:
var obj = {}, element = "test";
obj[element] = 333333;
var time1 = new Date().getTime(); // start timestamp
for (var i=0; i<1000; i++)
{
// here can be any code for measurement
var a = obj[element];
}
var time2 = new Date().getTime(); // end timestamp
var result = (time2 - time1) / 1000; // divide all time to number of iterations
alert(result + " ms");

Javascript using different configurations for different outputs

Hi being a complete and utter idiot at the moment, where I have staring at this stuff for hours and now have no clue what I am doing.
Basically in one which I will name here as product.js I have Global Variables fixed
var AREA_MAX_MAXX = 1000;
var AREA_MAX_MINX = 60;
these are being then being used within another js which I will call library.js with the following:
this.area_max_maxx = AREA_MAX_MAXX;
this.area_max_miny = AREA_MAX_MINX;
this.calcPos = function() {
var areaMaxWidth = this.area_max_maxx - this.area_max_minx;
What I want to do is remove the Global Variables and instead have it set up with arrays, so that whatever the array is the values will be set forarea_max_maxx
Can anyone help me out there??? Am I making sense?
You mean like this?
this.minAndMax = [60, 1000];
this.calcPos = function() {
var areaMaxWidth = this.minAndMax[1] - this.minAndMax[0];
}
I would recommend instead using an object:
this.areaParameters = {min: 60, max: 1000}
this.calcPos = function() {
var areaMaxWidth = this.areaParameters.max - this.areaParameters.min;
}
Later, you can just say this.areaParameters.max = 3000 and next time calcPos gets called it will use the new value.
This is not possible. You are passing a value not a reference here:
this.area_max_maxx = AREA_MAX_MAXX;

Sorting multidimensional array jquery/javascript

var klas4 = [];
klas4[2] = [];
klas4[2]["hour"] = 1;
klas4[2]["teacher"] = "JAG";
klas4[2]["group"] = "V4A";
klas4[2]["subject"] = "IN";
klas4[2]["classroom"] = "B111";
klas4[0] = [];
klas4[0]["hour"] = 6;
klas4[0]["teacher"] = "JAG";
klas4[0]["group"] = "V4B";
klas4[0]["subject"] = "IN";
klas4[0]["classroom"] = "B111";
klas4[1] = [];
klas4[1]["hour"] = 4;
klas4[1]["teacher"] = "NAG";
klas4[1]["group"] = "V4A";
klas4[1]["subject"] = "NA";
klas4[1]["classroom"] = "B309";
This multidimensional array needs to be sorted by hour, ascending. The problem is, I don't know how to sort an multidimensional array. The first dimension (0, 1 and 2), needs to be changed, according to the hour, but all other details from dimension 2 (teacher, group etc.) also need to change from index, because otherwise the data is mixed.
You don't know how many indexes there are. In this example, the correct sequence should be: klas4[2][...], klas4[1][...], klas[0][...]
In PHP there's a certain function multisort, but I couldn't find this in jQuery or JavaScript.
klas4.sort( function(a,b){ return a.hour - b.hour } );
should do it.
It helps to think of klas4 not as a multi-array but as 1 array of objects.
Then you sort the objects in that array with a sort function.
The sort function takes 2 objects and you must return which one comes first.
You should read on sort() for Array, google that.
Also, as others have commented; the entries for klas4 are really objects, you should use
klas4[2] = {};
or even better
klas4[2] = { hour:1 , teacher:"JAG" , group:"V4A" , subject: "IN" };
Finally, I assume you are a native Dutch or German speaker, as I am. I would strongly suggest to name all your variables in English, class4, not klas4. It is the right, professional thing to do.

Categories