I'm trying to manipulate an array inside a for loop, where I want to add an item to the end of the array and delete an element at the beginning of the array, like this:
var internal = new Array();
for(var i = 0; i < 1000; i++) {
internal[i] = Math.floor(Math.random() * 37);
internal.shift();
console.log(internal.length);
}
The problem is that it looks like shift() doesn't work inside the loop, in fact, no element is deleted from the array!
Is there a solution?
Here JsFiddle
It reduces by one every time, but you are growing it every time by accessing it with the array index accessing. Instead of
internal[i] = Math.floor(Math.random() * 37);
use
internal.push(Math.floor(Math.random() * 37));
For example,
var internal = [];
internal[3] = "thefourtheye";
console.log(internal);
Output
[ , , , 'thefourtheye' ]
It made space for the first three elements and added the element at the index specified. So, it will keep the array growing.
Note: Use [] to create a new array, instead of new Array()
because you are using a hard coded index, try
var internal = new Array();
for(var i = 0; i < 1000; i++) {
internal.push(Math.floor(Math.random() * 37));
internal.shift();
console.log(internal.length);
}
Demo: Fiddle
//test
var arr = [];
arr[50] = 1;
console.log('arr.length', arr.length);
will print 51 not 1
Related
I want to get random names from the nameArray and each time delete that element, so that in the end, I have got all names and the nameArray is empty. Nothing displays in the console.
let i;
let nameArray = ['Chara','Lisette','Corine','Kevin','Carlee'];
while(i < nameArray.length){
let name = nameArray[ Math.floor( Math.random() * nameArray.length )];
console.log(name);
delete nameArray[i];
}
i is never initialized nor updated, so the while loop doesn't make too much sense.
You can try this instead:
let nameArray = ['Chara','Lisette','Corine','Kevin','Carlee'];
while(nameArray.length > 0) { // while the array is not empty
let i = Math.floor(Math.random() * nameArray.length); // pick a random element index
console.log(nameArray[i]); // print the element
nameArray.splice(i, 1); // remove the element from the array
}
I am trying to make a sorting visualizer. But when I am creating a array using following code, every time when I create a new array I am getting the same array as previous one! I have to refresh the page to get a new array. What will I have to do in order to get different array without refreshing through browser.
let sortingMethod = "";
let array = [];
function between(max) {
return Math.floor(Math.random() * Math.floor(max));
}
function createArray() {
for(let i = 0; i < 20; i++) {
array.push(between(20));
}
let arena = document.querySelector(".arena");
arena.innerHTML = '';
for(let i = 0; i < 20; i++) {
let element = document.createElement('div');
element.setAttribute('class', 'element');
console.log(array[i]);
element.style.height = (array[i] * 20) + "px";
arena.appendChild(element);
}
//console.log("created");
}
let create = document.getElementById("create");
create.addEventListener('click', createArray);
You are never clearing your array. So, each time you call createArray, new values are just appended to the end of the already filled array, but you only use first 20 values each time.
To solve your problem, just write this part of code let array = []; inside your createArray function.
I'm trying to create a 2D array with javascript that I can ultimately put inside a nested loop to extract X/Y information.
What am I doing wrong here?
function createMatrix(){
let colcount = 0;
let rowcount = 0;
var pixel_array = new Array();
var y_array = new Array();
for (var i = 0; i <= 100; i++){
var checker = (i+1) % 10;
if(checker == 0){
y_array.push(i);
//create new X array
pixel_array[rowcount] = [];
//push column data into row array
pixel_array[rowcount].push(y_array);
//create new Y array
var y_array = new Array();
//increment row counter
//reset column counter
parseInt(rowcount++);
colcount = 0;
}else{
y_array.push(i);
parseInt(colcount++);
}
}
//sanity check: spit out the matrix
for (var x=0; x<10;x++){
for(var y=0; y<10; y++){
console.log(pixel_array[x][y]);
}
}
}
I was expecting to call a specific X/Y 'coordinate' and extract the information from that 'cell'. However, I'm getting an error that basically says the [Y] part of the array is not defined.
Looking at console.log and console.table - I can see the X array is filled, but it isn't like I'd expect, just a list of numbers not another array.
Edit: To be more specific, my goal is to create a 2D array from a single For loop. The nested for loop at the bottom of the code is shown as an example of how I would like to call the 'cells' [X][Y].
This code:
pixel_array[rowcount] = [];
//push column data into row array
pixel_array[rowcount].push(y_array);
creates a new array, stores it in pixel_array[rowcount], and then pushes y_array into it. So at that point, you have an array (pixel_array) with an entry that's an array (the one you created via []), with an entry that's an array (y_array). That's closer to a 3D array than a 2D array.
You may be overcomplicating it a bit. I can't quite make out what you want your final array to be, so here's an example of creating a 3x4 "2D array" (it isn't really¹, it's an array of arrays, but...) with the numbers 1-12 in it, see comments:
// Create the outer array
var array = [];
for (var x = 0; x < 4; ++x) {
// Create the inner array for this row and store it in `array[x]`
var inner = array[x] = [];
for (var y = 0; y < 3; ++y) {
// Set the value of the inner array at `y`,
// which is also `array[x][y]`
inner[y] = (x * 3) + y + 1;
}
}
console.log(array);
.as-console-wrapper {
max-height: 100% !important;
}
In a comment you've said:
I want to create a 2D array from a single For loop. So in my example I'm looping 0-99, with the expected result being a 10x10 'matrix' (0-9, 10-19, 20-29, etc).
Here's an example doing that:
// Create the outer array
var array = [];
var inner;
for (var n = 0; n < 100; ++n) {
// Time to create a new inner array?
if (n % 10 === 0) { // It's important that this condition is true on the first loop iteration
inner = [];
array.push(inner);
}
// Add this `n` to the current inner array
inner.push(n);
}
console.log(array);
.as-console-wrapper {
max-height: 100% !important;
}
¹ "it isn't really, it's an array of arrays" - JavaScript doesn't have multi-dimensional arrays. It has arrays that can contain other arrays. For many purposes, the distinction doesn't really matter, but it means (amongst other things) that the arrays can be jagged: Not all entries in the outer array have to have the same length. (In fact, they don't even have to be arrays.)
Observe:
var groupedLinks = new Array;
for(var i = 0; i < 5; i++) {
linkName = "59notgonnawork" + i;
groupedLinks[linkName] = new Array;
}
I would have expected the result to be the array groupedLinks to be filled up with 5 new keys, the value would be 5 empty arrays.
The actual result in extendscript would be ... grouplinks ... empty.
If I would change this example to be:
var groupedLinks = new Array;
for(var i = 0; i < 5; i++) {
linkName = "notgonnawork" + i;
groupedLinks[linkName] = new Array;
}
It would work perfectly. The only change is the missing "59" at the start of the string used for the array key.
Note that this works perfectly when I run it in console for chrome or firefox. It seems to be indesign and/or extendscript fooling around.
Anything have any ideas why ? I've meanwhile worked around the problem but I'm intrigued.
I would have expected the result to be the array groupedLinks to be filled up with 5 new keys, the value would be 5 empty arrays.
That's exactly what it does, but the way you're viewing the data is likely concealing it because you're not using the proper data structure. Also, property access won't work without using [] because identifiers may not start with a number, so you'd need:
groupedLinks["59notgonnawork0"]
What you're doing isn't meant for arrays, which are expecting sequential numeric indices (though they can technically be assigned other properties too). The type of structure you should be using is a plain object instead.
var groupedLinks = {};
for(var i = 0; i < 5; i++) {
const linkName = "59notgonnawork" + i;
groupedLinks[linkName] = new Array; // Array? plain Object? Depends on its use.
}
Why not trying to push the value in the array on each iteration.
var groupedLinks = new Array;
for(var i = 0; i < 5; i++) {
linkName = "59notgonnawork" + i;
groupedLinks.push(linkName);
}
ExtendScript Arrays are great for stocking data per indeces. If you need key/values objects, why not use… Objects ?
var groupedLinks = {};
for(var i = 0; i < 5; i++) {
linkName = "59notgonnawork" + i;
groupedLinks[linkName] = "Whatever…";
}
alert( groupedLinks["59notgonnawork0" ] ); //"Whatever…"
i am a javascript newbie. I have a 9*9 grid for my sudoku game. The html is such that each box of the grid is an inputelement with id like r1c4 where 1 is the row number and 4 is column number. I have half filled grid.I needed to store all the numbers in the grid in a two dimensional array.I have created the following function fo:
function getValues(){
var grid = new Array();
var colData = new Array();
var targetId;
for(var i=1;i<=9;i++)
{
for(var j=1;j<=9;j++)
{
targetId = 'r' + i + 'c' + j;
colData[j-1] = document.querySelector('#'+targetId).value;
}
grid[i-1] = colData;
console.log(grid[i-1]); // here logged correctly
}
return grid; // here returned wrong
}
The problem i am facing is that the returned array consists of only the last element repeated 9 times. I am logging the stored value every time by using console.log(grid[i-1]); and it is giving correct results.I am not getting it.
Regards.
grid[i-1] = colData;
You are not copying colData to grid[i-1], but simply making grid[i-1] a reference to colData. So, all the elements in your array are just references to the same object, colData.
To fix this problem, you need to create a new Array on every iteration. So, I would have done it like this
function getValues() {
var grid = [], colData, targetId;
for (var i = 1; i <= 9; i++) {
colData = []; // new Array on every iteration
for (var j = 1; j <= 9; j++) {
targetId = 'r' + i + 'c' + j;
colData.push(document.querySelector('#' + targetId).value);
}
grid.push(colData);
}
return grid;
}
You need to create a new colData per iteration rather than using the same one each time.
for(var i=1;i<=9;i++)
{
var colData = new Array();
...
Try either moving colData = new Array() (or better, colData = [];) inside the i for loop.
OR use grid[i-1] = colData.slice(0);.
Either way, you need to create a new array for each row, not just re-use the old one.
You're using the same Array object for every single column, and just overwriting the values. You're pushing 9 references to that same array into your grid.
You need to move var colData = new Array(); inside the loop so you're making a new Array for each column.