I'm stuck trying to figure out how to loop trough nested arrays.
I have an array called worldShapes that contains child arrays. I want to loop trough the parent array and get all the child arrays from it.
Here's my attempt:
//Nested array
worldShapes = [
[33,108,66,141,99,174,99,207,132,207,165,207,165,240],
[132,306,165,306,165,339,165,372,132,405,99,405,99,438,132,438,165,438],
[198,339,231,339,264,372,297,372,330,405,363,438,396,438],
[198,174,198,273,231,306,264,306],
[231,174,231,240,264,273,297,273],
[396,306,462,306,495,339,495,372,528,405,528,438,561,438,594,471],
[660,504,561,504,495,504]
];
//trying to loop trough each item in the child array
(function(){
var wShapes = worldShapes; //create a local variable
var wLen = wShapes.length; //store the length as a variable
for (var i = 0; i < wLen; i++) {
for (var j = 0; j < wShapes[i].length; j++){
console.log(wShapes[i][j]); //this is propably wrong, trying to access the current child item of the current parent array
}
}
})
Just add (); to the very end of your code ;-)
You've simply forgotten to invoke your anonymous function
To execute the function, add ()
(function () {
var wShapes = worldShapes; //create a local variable
var wLen = wShapes.length; //store the length as a variable
for (var i = 0; i < wLen; i++) {
for (var j = 0; j < wShapes[i].length; j++) {
console.log(wShapes[i][j]); //this is propably wrong, trying to access the current child item of the current parent array
}
}
}()); // here
Fiddle
Related
So I'm just beginning to code and have learnt only basic codes and I have created arrays dynamically with:
for (var j=0; j<20; j++) {
this["row"+j] = [];
for (var i=0; i<10; i++) {
["row"+j].push("false");
}
}
but now I want to make it so that I can push items into the previously created row1[], row2[], etc... so that it could be like row1[false, false...] and row2[false, false...] Is there a way to do that?
It is not clear what this is referring here. Rather I will suggest to create an object and in that object keys will be ["row" + j], the value of which will be an [] and then inside the nested loop push value to that array
let obj = {};
for (var j = 0; j < 20; j++) {
obj["row" + j] = [];
for (var i = 0; i < 10; i++) {
obj["row" + j].push("false");
}
}
console.log(obj)
If you want to create arrays not inside object but like normal arrays you can use window and then variable name to create variable.
Normally when you declared varibale in will be inside window object(you can access it without writing window.{variable name}). So you can take advantage of window to created dynamic variable.
for (var j = 0; j < 20; j++) {
window["row" + j] = []; //<-----use window to create dynamic array
for (var i = 0; i < 10; i++) {
window["row" + j].push("false");
}
}
row1[0] = "true"; // editing content of array
console.log(row1,row2);
In the above we have created 20 variable name row0,row1,.... and you can directly access it like normal arrays.
I have both an object and an array:
var elementsArr = [];
var elements = {
polygon: 734,
infoContent: "huhu",
id: 0
}
I am going to have multiple "elements" and push each one into "elementsArr".
for(var i=0; i<20; i++){
elements.id = id +=1;
elementsArr.push(elements);
}
My problem now is how to access a specific "id" within the object elements, within the array elementsArr and pushing this into another array.
I tried this but it doesn't seem to be working:
var ids = [];
for(var m=0; m<elementsArr.length; m++){
if(elements.id == elementsArr[m]){
ids.push(elements.id);
}
How do I do this?
Your code is pushing the same object onto the array over and over again.
One way to fix that would be to write a function to get a new element:
function Element(id) {
return {
polygon: 734,
infoContent: "huhu",
id: id
};
}
for(var i=0; i<20; i++){
elementsArr.push(Element(i));
}
If there are going to be a lot of elements, and the "id" values are all relatively small numbers, you'd be better off storing the elements such that the "id" is also the index:
for (var i = 0; i < 20; i++)
elementsArr[i] = Element(i);
To get the element with "id" 17, then:
var element17 = elementsArr[17];
If you really want to search, however, you can use .find():
var element17 = elementsArr.find(function(elem) { return elem.id === 17; });
or a simple loop:
for (var i = 0; i < elementsArr.length; ++i) {
if (elementsArr[i].id === 17) {
// found it!
}
}
You can extract the "id" values from the array with a simple call to .map():
var ids = elementsArr.map(function(elem) { return elem.id; });
or another for loop:
var ids = [];
for (var i = 0; i < elementsArr.length; ++i)
ids.push(elementsArr[i].id);
There are a couple of ways to do this. If you are able to work in ES6 then a WeakMap would be great.
However, I'm going to give you an ES5 instead.
Option 1 Loop through the data.
If you aren't accessing the data often, then looping through as you've done so may be the best choice.
Option 2 Set up your own index
On the other hand, if you need faster lookup, you can set up your own separate index to look things up.
var elementsLookup = {}; // Create an empty object.
for(var i=0; i<20; i++){
elements.id = id +=1;
elementsLookup[id] = elements; // Stash off a copy
elementsArr.push(elements);
}
Then you can look things up with a
var elem = elementsLookup[2]; // Get the element with an id of 2.
It is easy to do it with Array prototyping. Here is a function findById
Array.prototype.findById = function(id){
for(var x = 0 ; x < this.length; x++){
if(this[x].id == id){
return this[x];
}
}
return false;
}
You can use this function to recieve any id from the array or false if it does not exists
elementsArr.findById(17);
I want to clone some players inside my .shuffler div. Because I attached click-listeners to the .player divs I want to append the entire object instead of just their HTML.
When I loop through the code below I do get the correct result when logging playerClones[j] in the each loop but it doesn't append anything.
Any ideas on how to clone my players and append every player 25 times to my .shuffler. without losing the click listener?
this.amountOfDuplicates = 25;
var playerClones = [];
this.parentObject.find('.player').each(function () {
playerClones.push(jQuery(this).clone());
});
for (var i = 0; i < this.amountOfDuplicates; i++) {
for (var j = 0; j < playerClones.length; j++) {
this.parentObject.find('.shuffler').append(playerClones[j]);
}
}
Fiddle here!
Normally when you use $(this).clone(), everything of the object is cloned except the click listener.
It is better if you could declare a function like this and call it every time u clone the object.
attachClickToClone = function() {
$('.player').on('click', function() {
//to-do-function
}
}
And call it like this.
for (var i = 0; i < this.amountOfDuplicates; i++) {
for (var j = 0; j < playerClones.length; j++) {
this.parentObject.find('.shuffler').append(playerClones[j]);
}
}
attachClickToClone();
In the below code, I am getting "push is not a function" error. Can anyone please let me know what I am doing wrong here? I am trying to create 2D array in Javascript.
var myArray = new Array(4);
myArray = ["0","0","0","0"];
for (var i=0; i<myArray.length; i++) {
myArray[i].push("ID");
myArray[i] = new Array(1);
for (var j=0; j<myArray[i].length; i++) {
myArray[i][j].push("Array[j]");
}
}
Firebug is pointing me to:
myArray[i].push("ID");
For this line I am getting "TypeError: myArray[i].push is not a function"
Final array it should look like is:
[ID,"SomeValue1"],
[ID,"SomeValue2"],
[ID,"SomeValue3"]
And I cannot hard code, I need to create this dynamically based on data from DB
myArray[i].push("ID");
Is invalid of course because it's a function defined for an Array not for it's elements.
valid syntax would be
myArray.push("ID");
To know more about array.push() go here.
This will create your example.
var myArray = new Array(4);
for (var i = 0; i < myArray.length; i++) {
myArray[i] = ["ID", "SomeValue" + (i+1)];
}
But if you need to set data from a database, how is that being set in the Javascript? if it's in a different array you could do the following:
var dbArray = ["SomeValue1", "SomeValue2", "SomeValue3"];
var myArray = new Array(dbArray.length);
for (var i = 0; i < myArray.length; i++) {
myArray[i] = ["ID", dbArray[i]];
}
First of all, you can initialize Arrays using the Array Literal [] which should always be preferred
Then push is an Array method. So you have to call it on an Array
myArray[i] is the Element of the Array, myArray the Array
var arr = [];
for (var i = 0; i < 5;i++) {
arr.push = []; //Uses the Arrays push method
for ( var j = 0; j < 5; j++)
arr[i][j] = "Asd"; //Sets an Element
}
console.log(arr);
And as you see don't need to "Dim" an Array, you just can assign an Array to a Variable and start pushing Elements in it.
As you can see in the example, the first time
push is directly after arr, its the Arrays Method and appends a new Element to the Array
And in the second Example it accesses the Element and assigns it a value directly
What you are doing in your code is trying to invoke the push method on an Elements Array
Assume i is 0 Then
'myArray[i]' is "0" and the String "0" has no Method push.
But you can directly assing a new String to the Element like.
myArray[i] = "ID"
I am having issues with a couple arrays below and the match method. On my page I call the Checkout() function and it sets a temporary array equal to the array I've been building with different options. It then loops through the temporary array and removes html from one of the elements. The issue is that when I alert the array Remote.Cart.products before the loop it is exactly as it was built, but when I call the function again the exact same alert shows the new updated values even though I am not modifying the Remote.Cart.products array anywhere in the function.
function Checkout() {
tmp = null;
tmp = Remote.Cart.products;
alert( Remote.Cart.products );
for ( i = 0, li = tmp.length; i < li; i++ ) {
for ( j = 0, lj = tmp[ i ][1].length; j < lj; j++ ) {
tmp[ i ][1][j][1] = tmp[ i ][1][j][1].match(/<a\s+[^>]*href="([^\"]*)"[^>]*>(.*)<\/a>/i)[2];
}
}
}
Your help / insight is much appreciated!
You are using the same array. Just a different variable that points to the same array. In memory it's the same object.
You need to rebuild the array in your loop so that you can get an identical but new array.
More info on copying arrays and other objects can be found here: http://my.opera.com/GreyWyvern/blog/show.dml/1725165
Clint, you have to understand that tmp and Remote.Cart.products are different names for the same array. If you want to clone the array, do:
var tmp = [];
for(var i = 0; i < Remote.Cart.products.length; i++)
{
tmp[i] = []
for(var j = 0; j < Remote.Cart.products[i].length; j++)
{
tmp[i][j] = [];
for(var k = 0; k < Remote.Cart.products[i][j].length; k++)
{
tmp[i][j][k] = Remote.Cart.products[i][j][k].slice();
}
}
}
EDIT: Nesting corrected thanks to Squeegy
"even though I am not modifying the Remote.Cart.products array anywhere in the function"
tmp = Remote.Cart.products;
...
tmp[ i ][1][j][1] = ...
It sure looks like you are.