Dynamic add a multi-dimension array in javascript or jquery - javascript

The problem is I need to add a multi dimension array dynamically, please look at the following example:
var list = [];
var listname;
var height;
var width;
list.push(listname);
list[listname] = height;
list[listname] = width;
the code above is not what I expected , which should be [listname => [[0]=>height,[1]=>width]], what can I do if I do not want to create an array for listname, can I dynamic add a mulit dimension array ? thanks.

Don't confuse Arrays with Maps. They are different fundamental data-types1
var myLists = {}; // name => array
var listname = "stuff"; // why not?
var height = 1;
var width = 2;
// there is no Object.push, but we can assign a property by name
myLists[listName] = [height];
// then we can Array.push into the array we just assigned
myLists[listName].push(width);
Then, myLists:
{
stuff: [1, 2]
}
1JavaScript mostly maintains this distinction - if one doesn't add random properties to Arrays or otherwise fake an Object to behave like an array.

Related

Trying to create a matrix with random numbers in JavaScript produces a matrix where all the rows are the same

When I try to create a matrix with random numbers, the matrix rows all appear the same. How do I fix this? The code for the problem is:
var sudokuRowMatrix = [];
var numbers = [];
var randomizedArray = [];
var sudokuColumnArray = [];
for(i=0;i<=8;i++){
numbers[i]=i+1;
sudokuRowMatrix[i] = [];
sudokuColumnArray[i] = [];
}
function RandomizeArray(array){
for(arrayIndex=0;arrayIndex<=8;arrayIndex++){
randomArrayIndex = Math.floor(Math.random()*9);
randomArrayIndex2 = Math.floor(Math.random()*9);
placeHolder = array[randomArrayIndex];
array[randomArrayIndex]=array[randomArrayIndex2];
array[randomArrayIndex2] = placeHolder;
}
return array;
}
for(rowNumber=0;rowNumber<=8;rowNumber++){
sudokuRowMatrix[rowNumber] = RandomizeArray(numbers);
}
When you call RandomizeArray(numbers) you pass the numbers array as a reference.
This means, that you always shuffle the same array and set it as a row in your Sudoku matrix and therefore shuffle all of your rows since they all hold the same reference.
An easy way to fix this, is to destructure your array before passing it to your method:
sudokuRowMatrix[rowNumber] = RandomzieArray([...numbers]);
You can find my source here.

How to assign empty array to dynamic property in javascript?

Trying to add empty array to dynamic property, then fill the array dynamically. Contents of array are unknown until runtime and could be nothing.
Here is the code which does work in jsfiddle but not working in my app - so I'll have to dig deeper.
var ref = {s:5, d:{a:100, b:50}}
bigObject = {}
bigObject.object = {};
for (var i = 1;i<10;i++){
var n = 's'+i
bigObject.object[n] = []
}
bigObject.object['s'+ref.s].push(ref.d);
console.log(bigObject)

cannot iterate through array and change value in JS

I have to iterate through an array, change one of its values, and create another array refelecting the changes.
this is what I have so far:
JS:
var arr = new Array();
arr['t1'] = "sdfsdf";
arr['t2'] = "sdfsdf";
arr['t3'] = "sdfsdf";
arr['t4'] = "sdfsdf";
arr['t5'] = "sdfsdf";
var last = new Array();
for (var i = 0; i <= 5; i++) {
arr['t2'] = i;
last.push(arr);
}
console.log(last);
Unfortunately, these are my results
As you can see, I am not getting the results needed as 0,1,2.. instead I am getting 2, 2, 2..
This is what i would like my results to be:
How can I fix this?
You have to make a copy, otherwise you are dealing with reference to the same object all the time. As it was said before - javascript does not have associate arrays, only objects with properties.
var arr = {}; // empty object
arr['t1'] = "sdfsdf";
arr['t2'] = "sdfsdf";
arr['t3'] = "sdfsdf";
arr['t4'] = "sdfsdf";
arr['t5'] = "sdfsdf";
var last = new Array();
for (var i = 0; i <= 5; i++) {
var copy = JSON.parse(JSON.stringify(arr)); //create a copy, one of the ways
copy['t2'] = i; // set value of its element
last.push(copy); // push copy into last
}
console.log(last);
ps: you can use dot notation arr.t1 instead of arr['t1']
The array access with ['t2'] is not the problem. This is a regular JavaScript feature.
The problem is: You are adding the SAME array to "last" (5 times in code, 3 times in the screenshot).
Every time you set ['t2'] = i, you will change the values in "last" also, because they are actually just references to the same array-instance.
You must create a copy/clone of the array before you add it to "last".
This is what will happen in all languages where arrays are references to objects (Java, C#...). It would work with C++ STL though.

Create an array or object of elements with the same dynamic class

I currently the following jQuery collection / object:
[li.row-0, li.row-1, li.row-2, li-row-2, li.row-2, li.row-3]
Each class name is dynamically added to each element by a previous method. The only consistent part of the class name is row-. The number can be anywhere from 0 - ∞.
I want to create a new array or object of elements that are grouped by same dynamic class name:
[li.row-0]
[li.row-1]
[li.row-2, li.row-2, li.row-2, li.row-2]
[li.row-3]
The above is just a guess of the outcome, as I am not 100% sure how best to achieve this.
The aim is to be able to loop through .row-0, .row-1, .row-2, .row-3 and do something with the elements in each individual row.
I would do this :
var map = [].reduce.call(arr, function(map, v){
(map[v.className]||(map[v.className]=[])).push(v);
return map;
}, {});
var arr2 = [];
for (var className in map) arr2.push(map[className]);
The reduce builds a map having as keys the class names and with values the arrays of the elements having that class name.
I use [].reduce.call(arr, instead of arr.reduce( so that it works for standard arrays, jQuery collections, nodelists, etc.
Then the loop builds an array from that map. You might find the map more useful than the final array.
This shows you a general way of achieving this, though you're probably using elements rather than strings, but hopefully this will help
var tst = ['li.row-0','li.row-1','li.row-2','li.row-2','li.row-2','li.row-3'];
var grouped = [];
for(var i in tst)
{
var text = tst[i];
var num = text.replace('li.row-','');
if(!grouped[num]) grouped[num] = [];
grouped[num].push(text);
}
console.log(grouped);//[["li.row-0"], ["li.row-1"], ["li.row-2", "li.row-2", "li.row-2"], ["li.row-3"]]
Using elements:
var tst = [li.row-0,li.row-1,li.row-2,li.row-2,li.row-2,li.row-3];
var grouped = [];
for(var i in tst)
{
var text = tst[i].className;
var num = text.replace('row-','');
if(!grouped[num]) grouped[num] = [];
grouped[num].push(text);
}
console.log(grouped);//[["li.row-0"], ["li.row-1"], ["li.row-2", "li.row-2", "li.row-2"], ["li.row-3"]]
This method is more verbose and allows more complex grouping if need be (if other attributes come into play)
I would do something like the following:
var arr = ['li.row-0', 'li.row-1', 'li.row-2', 'li.row-2', 'li.row-2', 'li.row-3'];
var result = {};
$.each(arr, function (index, item) {
var ind = item.toString().split('row-')[1];
(result[ind] || (result[ind] = [])).push(item);
});
console.log(result);

javascript how to find number of children in an object

is there a way to find the number of children in a javascript object other than running a loop and using a counter? I can leverage jquery if it will help. I am doing this:
var childScenesObj = [];
var childScenesLen = scenes[sceneID].length; //need to find number of children of scenes[sceneID]. This obviously does not work, as it an object, not an array.
for (childIndex in scenes[sceneID].children) {
childSceneObj = new Object();
childSceneID = scenes[sceneID].children[childIndex];
childSceneNode = scenes[childSceneID];
childSceneObj.name = childSceneNode.name;
childSceneObj.id = childSceneID;
childScenesObj .push(childSceneObj);
}
The following works in ECMAScript5 (Javascript 1.85)
var x = {"1":1, "A":2};
Object.keys(x).length; //outputs 2
If that object is actually an Array, .length will always get you the number of indexes. If you're referring to an object and you want to get the number of attributes/keys in the object, there's no way I know to that other than a counter:
var myArr = [];
alert(myArr.length);// 0
myArr.push('hi');
alert(myArr.length);// 1
var myObj = {};
myObj["color1"] = "red";
myObj["color2"] = "blue";
// only way I know of to get "myObj.length"
var myObjLen = 0;
for(var key in myObj)
myObjLen++;

Categories