Add elements to 2D array in jquery [duplicate] - javascript

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to create a two dimensional array in JavaScript?
I want to push elements to 2D array,
My code is,
var results = [];
var resultstemp = [];
function bindlinks(aamt,id1) {
resultstemp=results;
imagesArray.push($("#image1").mapster("get"));
if(results.length==0)
{
results.push([id1]);
}
else
{
var ck=0;
var lng=results.length;
for (var i = 0; i < lng; i++) {
if(results[i]==id1)
{
ck=1;
results = jQuery.grep(results, function(value) {
return value != id1;
});
}
}
if(ck==0)
{
results.push(id1);
}
}
I want to push id as well as aamt to array. Here i am pushing only id to array. I am not sure about how to add aamt to second position in 2D array.
Help me please,
Thank you

Change the declaration as follows:
var results = new Array();
and change the push as follows:
results.push([id1,aamt]);
Hope it would help

The logic behind the method to push two separate values in the same array evenly is something like this:
var array = [];
function push(id1, aamt) {
for (var i= 0; i < 10; i++) {
if (i%2 == 0) {
array.push(id1);
}
else {
array.push(aamt);
}
}
}
push(10, 12);
console.log(array); // 10, 12, 10, 12.....
Take note i abstracted the code quite a bit, because for me was not too obvious what the code should have to do, but the principle is simple: use the modulo (%) operator to test if the value is odd or even. If odd add the first value if even add the second value.
Hope it helps.

Related

JavaScript array of classes behaving as clones? [duplicate]

This question already has answers here:
Copy array by value
(39 answers)
Closed 2 years ago.
So I've been trying to implement a NEAT algorithm in JS, but I'm missing something because when I try to mutate the genomes in my population, they all come out with the same mutation, as in they behave as complete clones, every single genome is the same at the end. Not sure why the array of glasses seems to share connections and nodes when they each have been declared as a new object, I'm definitely missing something I just do not know what, here's the code:
let startingNode = [];
let inNode1 = new Node("INPUT", 0)
let inNode2 = new Node("INPUT", 0)
let outNode1 = new Node("OUTPUT", 100000)
startingNode.push(inNode1);
startingNode.push(inNode2);
startingNode.push(outNode1);
let startingGenome = new Genome([], startingNode);
let population = new Population(20, startingGenome);
class Population {
constructor(populationSize, startingGenome) {
this.populationSize = populationSize;
this.population = [];
let genomeThings = startingGenome.copyGenome();
while (this.population.length < this.populationSize) {
this.population.push(new Genome(genomeThings.connections, genomeThings.nodes));
}
this.mutate();
console.log(this.population);
}
mutate() {
for (let genome of this.population) {
if (Math.random() < MUTATION_RATE) {
`genome.weightMutation()
}
}
}
class Genome {
constructor(connections, nodes) {
this.connections = connections;
this.nodes = nodes;
}
copyGenome() {
return {connections: this.connections, nodes: this.nodes};
}
After visiting a similar question: How do I correctly clone a JavaScript object?
I realised the clone method was wrong and was copying the objects in the wrong way (I don't understand enough about it to explain it really). But after creating an empty genome, and individually pushing each connection and node I managed to get it so the connections and nodes in seperate genomes no longer comflict with each other, if anyone knows precisely why this happens I would love to know.
copyGenome() {
let clonedGenome = new Genome([], []);
for (let x = 0; x < this.connections.length; x++) {
clonedGenome.connections.push(this.connections[x]);
}
for (let x = 0; x < this.nodes.length; x++) {
clonedGenome.nodes.push(this.nodes[x]);
}
return clonedGenome;
}

JS multidimensional array spacefield

i wanna generate a 3x3 field. I want to do this with JS, it shall be a web application.
All fields shall inital with false. But it seems so that my code is not working correctly, but i don't find my fault. The goal is, that every spacesector is accessible.
Thats my idea:
// define size
var esize = generateSpace(3);
}
space[i] = false is replacing the array with a single boolean value false, not filling in all the entries in array you just created. You need another loop to initialize all the elements of the array.
function generateSpace(x) {
var space = [];
for (var i = 0; i < x; i++) {
space[i] = [];
for (var j = 0; j < x; j++) {
space[i][j] = false;
}
}
return space;
}
Also, your for() loop condition was wrong, as you weren't initializing the last element of space. It should have been i < space.length.
And when it's done, it needs to return the array that it created.
Since I got somewhat bored and felt like messing around, you can also initialize your dataset as shown below:
function generateSpace(x) {
return Array.apply(null, Array(x)).map(function() {
return Array.apply(null, Array(x)).map(function() {
return false;
});
});
}
The other functions work equally well, but here's a fairly simply looking one using ES6 that works for any square grid:
function generateSpace(x) {
return Array(x).fill(Array(x).fill(false));
}

Looping through objects in an array JS

I'm putting together this script which pulls two child elements from a containing div #mini_ads, adds them to an array. I want to be able to use the array to select them via index in order to manip. them individually.
I know I can just select them w/o even using an array of course, but I want this array as I may add multiple more elements later.
The issue is that I am not able to select the items individually by their index in the array. The current script I've got going is selecting and manipulating both objects in the array as if they're both index[0].
var miniAds = $('#mini_ads');
var elements = miniAds.children();
var changeWtime;
var adsArr = new Array();
var i = 0;
var x = 0;
adsArr.push(elements);
console.log(adsArr);
adsArr[i].css("display", "none");
var changeWtime = setInterval(function () {
for (x; x < 1; x++) {
return x;
while (x > i) {
adsArr[1].css("display", "block");
}
};
}, 5000);
console.log(x);
changeWtime;
I am not sure where I'm going wrong here. Assistance will be much appreciated. Thanks in advance.
Issues with your code
You're creating a double array when you push elements into 'adsArr':
adsArr.push(elements);
You're throwing a return statement in the for loop:
for (x; x < 1; x++ ){
return x;
// ...
You have a double loop for no reason while inside of the for.
Solution
I was going to explain the solution to this verbally, but after coding an example I realized that there is too much to explain this is another solution similar to yours:
var miniAds = $('#mini_ads'),
elements = miniAds.children(),
i = 2,
x = 0;
elements.hide();
var changeWtime = setInterval(function () {
if ( x < i ) {
$(elements[x]).show();
}
x++;
}, 5000);
Link to example on jsbin.
Hi u should push child divs as below function does and after that i believe u can perform ur task...
var adsArr= [];
$('#mini_ads').children().each(
function(i){
adsArr.push(this);
});
In plain Javascript use .styles()
.css() which is a JQuery method but not Javascript
ref http://www.w3schools.com/js/js_htmldom_css.asp

in javascript array find min max values [duplicate]

This question already has answers here:
Find the min/max element of an array in JavaScript
(58 answers)
Closed 9 years ago.
i have some arrays like this, the numbers in the array represents slots numbers
slots1 = {3,4,5,6}
slots2 = {1,2,3,4,5,6}
slots3 = {8,9,10}
i am finding whether the selected slots are successive or not.
first two arrays give correct min,max values.
but the third array is giving min = 10, max=9.
how to rectify it?
i am finding maximum value like this
for(var s=0;s<no_slots;s++)//finding maximum value of slots array
{
if(s == 0)
{
var slots_max = slots[s];
}
else
{
if(slots[s] > slots_max)
{
slots_max = slots[s];
}
}
}
Use the JS Math Object:
For the minimum: Math.min.apply(null,slots);
For the maximum: Math.max.apply(null,slots);
I am not sure why you function is not correctly working for your third case. You probably missed something silly like initialization or something similar to that.
As I have modified your some code and it is returning correctly. You can also make it shorter.
var slots = [8, 9, 10]
var slots_max = slots[0];
for (var s = 0; s < slots.length; s++) //finding maximum value of slots array
{
if (slots[s] > slots_max) {
slots_max = slots[s];
}
}
alert(slots_max);
Js Fiddle
You could instead try finding the minimum/maximum values using the Javascript Math library. This should return the correct result.
var min = Math.min.apply(null, slots3);
var max = Math.max.apply(null, slots3);
See this answer for more details.

How to maintain only a specific number of elements in a Javascript Array

I require to maintain only a specific number of elements in an Javascript array. Lets say only 10 items in the array. It should follow the FIFO concept, which means if there are 10 items on the array and a new item is added, then the item[0] should automatically be popped out of the array. Is there a way to do this or should I be doing the whole stuff programatically on Javascript array?
I'd probably create my own object that has an array in it:
var myArray = {
arr: [],
add: function(val) {
this.arr.unshift(val);
if (this.arr.length > 10) {
this.arr.length = 10;
}
}
};
for (var i = 0; i < 15; i++) {
myArray.add(i);
//alert(myArray.arr.length);
}​
http://jsfiddle.net/6Nevz/2/

Categories