Setting Double Array Values - javascript

I'm getting an error when I'm trying to assign values to an empty 2D array.
It says Cannot set property '0' of undefined.
Why is this and how can I fix it so that I can assign values from a 2D array to a new empty 2D array?
var array = await data;
array = JSON.parse(array);
var activeArray = new Array();
var inactiveArray = new Array();
for (let i = 0; i < array.length; i++)
{
if (array[i][2] == "Active")
{
activeArray[i][0] = array[i][0];
activeArray[i][1] = array[i][1];
activeArray[i][2] = array[i][2];
}
else
{
inactiveArray[i][0] = array[i][0];
inactiveArray[i][1] = array[i][1];
inactiveArray[i][2] = array[i][2];
}
}

This effectively solved my problem.
var array = await data;
array = JSON.parse(array);
var activeArray = new Array();
var inactiveArray = new Array();
var activeArrayCounter = 0;
var inactiveArrayCounter = 0;
for (let i = 0; i < array.length; i++)
{
if (array[i][2] == "Active")
{
activeArray[activeArrayCounter] = new Array();
activeArray[activeArrayCounter][0] = array[i][0];
activeArray[activeArrayCounter][1] = array[i][1];
activeArray[activeArrayCounter][2] = array[i][2];
activeArrayCounter++;
}
else
{
inactiveArray[inactiveArrayCounter] = new Array();
inactiveArray[inactiveArrayCounter][0] = array[i][0];
inactiveArray[inactiveArrayCounter][1] = array[i][1];
inactiveArray[inactiveArrayCounter][2] = array[i][2];
inactiveArrayCounter++;
}
}

Related

Multidimentioanal arrays in JavaScript values not appending

I am trying to add values in a multidimensional array in JavaScript, but it doesn't seem to work. I get "variable not defined" error in snippet but can't see any variable which is not defined.
Does anyone have any idea what's going wrong here?
Many Thanks,
Hassam
var abc = "11:00, 11:10, 12:20,12:30";
var split = abc.split(",")
var limits = new Array();
var alltimes = [[],[]];
//var split = ["11:00", "11:10", "12:20","12:30"];
var x = 0;
for (var i = 0; i < split.length -1 ; i++) {
limits.push(split[i]);
// alert(split.length );
if(i%2 === 1) // If odd value
{
alert(limits);
for (var j = 0;j<2; j++)
{
// alert(limits[j]);
alltimes[x][j] = limits[j];
}
limits.length = 0;
x++;
}
// alert(split.length + 2);
//
}
alert(alltimes);
// console.log(abc)
This is my JavaScript code
$(document).ready(function(){
$('.timepicker').click(function(){
var ajaxurl = 'Ajax.php',
data = {'action': 'Hassam'};
$.post(ajaxurl, data, function (response) {
// $('#timepicker').timepicker('option', 'disableTimeRanges', [abc]);
var split = response.split(",");
var x = 0;
for (var i = 0; i < split.length -1 ; i++) {
limits.push(split[i]);
alert(split.length );
if(i%2 === 1) // If odd value
{
for (var j = 0;j<2; j++)
{
// alert(limits[j]);
alltimes[x][j] = limits[j];
}
limits.length = 0;
x++;
}
alert(split.length + 2);
//
}
alert(alltimes);
// console.log(abc)
});
There is very simple solution to achieve what you want.
var split = ["11:00", "11:10", "12:20", "12:30"];
var alltimes = [];
while (split.length) {
alltimes.push(split.splice(0, 2));
}
console.log(alltimes);

transferring items among several arrays in javascript

I have got a pretty complicated issue, I tried everything and its not working properly. So the conception is (i just copied the interesting part of it, otherwise it would be few hundred more lines) :
The program is a card game and 24 cards (4 different colors, one is always stronger,it is called ADU) are distributed randomly among 4 players (4 arrays). The table where you put down the cards are represented by "asztal" array. First the human player puts a card, then the computers should reach in this order:
If they have same color and higher value - pick that card
If they have same color and any value - pick that card
If they dont have matching color, any car from the special color set (for being simple, its the first card the loop would find in the array)
If they dont have matching color, nor card from special color set, than the first element of the array (player[0]).
If you run my code, you would see it is not grabbing 1/1/1 card from each array, but sometimes more. And those cards do disappear, and not getting into the asztal array. My code: (https://jsfiddle.net/daxa3pL2/)
function CardA(name,value,adu){
this.name = name;
this.value = value;
};
function CardB(name,value,adu){
this.name = name;
this.value = value;
};
function CardC(name,value,adu){
this.name = name;
this.value = value;
};
function CardD(name,value,adu){
this.name = name;
this.value = value;
};
CardA.prototype.adu = false;
CardB.prototype.adu = false;
CardC.prototype.adu = false;
CardD.prototype.adu = false;
var a9 = new CardA("Tök kilenc",0);
var a10 = new CardA("Tök tíz",10);
var aal = new CardA("Tök alsó",2);
var afel = new CardA("Tök felső",3);
var akir = new CardA("Tök király",4);
var aasz = new CardA("Tök ász",11);
var b9 = new CardB("Levél kilenc",0);
var b10 = new CardB("Levél tíz",10);
var bal = new CardB("Levél alsó",2);
var bfel = new CardB("Levél felső",3);
var bkir = new CardB("Levél király",4);
var basz = new CardB("Levél ász",11);
var c9 = new CardC("Makk kilenc",0);
var c10 = new CardC("Makk tíz",10);
var cal = new CardC("Makk alsó",2);
var cfel = new CardC("Makk felső",3);
var ckir = new CardC("Makk király",4);
var casz = new CardC("Makk ász",11);
var d9 = new CardD("Szív kilenc",0);
var d10 = new CardD("Szív tíz",10);
var dal = new CardD("Szív alsó",2);
var dfel = new CardD("Szív felső",3);
var dkir = new CardD("Szív király",4);
var dasz = new CardD("Szív ász",11);
CardC.prototype.adu = true;
var player1 = [c9,b9,b10,d9,a9,d10];
var player2 = [a10,aal,dal,c10,cal,bal];
var player3 = [bfel,bkir,basz,dfel,dkir,dasz];
var player4 = [afel,akir,aasz,cfel,ckir,casz];
var asztal = [];
asztal.push(player1.splice(0,1)[0]);
var player2card1 = function() {
for (i = 0; i < player2.length; i++) {
if (Object.getPrototypeOf(player2[i]) == Object.getPrototypeOf(asztal[0]) && player2[i].value > asztal[0].value) {
asztal.push(player2.splice(i,i+1)[0])
return
}
}
if (asztal.length == 1) {
for (i = 0; i < player2.length; i++) {
if (Object.getPrototypeOf(player2[i]) == Object.getPrototypeOf(asztal[0])) {
asztal.push(player2.splice(i,i+1)[0])
return
}
}
}
if (asztal.length == 1){
for (i = 0; i < player2.length; i++) {
if (player2[i].adu == true) {
asztal.push(player2.splice(i,i+1)[0])
return
}
}
}
if (asztal.length == 1) {
asztal.push(player2.splice(0,1)[0])
return
}
};
var player3card1 = function() {
for (i = 0; i < player3.length; i++) {
if (Object.getPrototypeOf(player3[i]) == Object.getPrototypeOf(asztal[0]) && player3[i].value > asztal[0].value) {
asztal.push(player3.splice(i,i+1)[0])
return
}
}
if (asztal.length == 2) {
for (i = 0; i < player3.length; i++) {
if (Object.getPrototypeOf(player3[i]) == Object.getPrototypeOf(asztal[0])) {
asztal.push(player3.splice(i,i+1)[0])
return
}
}
}
if (asztal.length == 2){
for (i = 0; i < player3.length; i++) {
if (player3[i].adu == true) {
asztal.push(player3.splice(i,i+1)[0])
return
}
}
}
if (asztal.length == 2) {
asztal.push(player3.splice(0,1)[0])
return
}
};
var player4card1 = function() {
for (i = 0; i < player4.length; i++) {
if (Object.getPrototypeOf(player4[i]) == Object.getPrototypeOf(asztal[0]) && player4[i].value > asztal[0].value) {
asztal.push(player4.splice(i,i+1)[0])
return
}
}
if (asztal.length == 3) {
for (i = 0; i < player4.length; i++) {
if (Object.getPrototypeOf(player4[i]) == Object.getPrototypeOf(asztal[0])) {
asztal.push(player4.splice(i,i+1)[0])
return
}
}
}
if (asztal.length == 3){
for (i = 0; i < player4.length; i++) {
if (player4[i].adu == true) {
asztal.push(player4.splice(i,i+1)[0])
return
}
}
}
if (asztal.length == 3) {
asztal.push(player4.splice(0,1)[0])
return
}
};
player2card1();
player3card1();
player4card1();
console.log(player1);
console.log(player2);
console.log(player3);
console.log(player4);
console.log(asztal);
So I debugged your code and there are two fundamental mistakes I found:
1: When you use the splice inside a loop, the indices will change. So, when you do for example
asztal.push(player2.splice(i,i+1)[0])
and put it inside a loop, the indices for player2 matching your condition will change as soon as you do the splice. So the next iteration of your loop will give incorrect results/ miss an index of an object that should be removed.
A possible solution to this is that instead of splice, inside your for-loops, just insert elements into asztal, and DON'T splice the parent. Then outside the loop, splice them from from the players using a FILTER function as follows:
var player2card1 = function() {
for (i = 0; i < player2.length; i++) {
if (Object.getPrototypeOf(player2[i]) == Object.getPrototypeOf(asztal[0]) && player2[i].value > asztal[0].value) {
asztal.push({name: player2[i].name, value: player2[i].value, prototype: player2[i].prototype});
player2[i].name = "delete";
return
}
}
player2.filter((each)=>{return each.name!== "delete"});
2: The second mistake (that I don't think is the problem here but still can cause trouble) is your use of "==". In Javascript, try to use '===' as far as possible as it also checks the type along with equality.
A little refactoring can go a long way to making this clear.
// define a card type class
function CardType(type, adu)
{
// This simply says that if ADU is undefined (not passed) then
// ADU should be set to false by default
this.adu = (typeof adu === 'undefined' ? false : adu);
this.type = type;
}
function Card(name, value, type)
{
this.name = name;
this.value = value;
this.type = type;
}
// Define our card types
var CardA = new CardType("A");
var CardB = new CardType("B");
var CardC = new CardType("C", true);// set to be ADU
var CardD = new CardType("D");
// Define our cards
var a9 = new Card("Tök kilenc",0, CardA);
var a10 = new Card("Tök tíz",10, CardA);
var aal = new Card("Tök alsó",2, CardA);
var afel = new Card("Tök felső",3, CardA);
var akir = new Card("Tök király",4, CardA);
var aasz = new Card("Tök ász",11, CardA);
var b9 = new Card("Levél kilenc",0, CardB);
var b10 = new Card("Levél tíz",10, CardB);
var bal = new Card("Levél alsó",2, CardB);
var bfel = new Card("Levél felső",3, CardB);
var bkir = new Card("Levél király",4, CardB);
var basz = new Card("Levél ász",11, CardB);
var c9 = new Card("Makk kilenc",0, CardC);
var c10 = new Card("Makk tíz",10, CardC);
var cal = new Card("Makk alsó",2, CardC);
var cfel = new Card("Makk felső",3, CardC);
var ckir = new Card("Makk király",4, CardC);
var casz = new Card("Makk ász",11, CardC);
var d9 = new Card("Szív kilenc",0, CardD);
var d10 = new Card("Szív tíz",10, CardD);
var dal = new Card("Szív alsó",2, CardD);
var dfel = new Card("Szív felső",3, CardD);
var dkir = new Card("Szív király",4, CardD);
var dasz = new Card("Szív ász",11, CardD);
var player1 = [c9,b9,b10,d9,a9,d10];
var player2 = [a10,aal,dal,c10,cal,bal];
var player3 = [bfel,bkir,basz,dfel,dkir,dasz];
var player4 = [afel,akir,aasz,cfel,ckir,casz];
var asztal = [];
// It doesn't really make sense to splice the array because
// you are changing the array.
// asztal.push(player1.splice(0,1)[0]);
// This line can be replaced with a simple:
asztal.push(player1[0]);
// This function has lots of redundant code and we can simplify it greatly
// as well as generalize it to work for each player
function getNextCard(player, card){
// By default we take the first card unless we find a better one along the way.
var matchCase2 = null, // same type, any value
matchCase3 = null, // special set
matchCase4 = player[0]; // any card
for(i = 0; i < player.length; i++)
{
// Check our first case
if(player[i].type.type == card.type.type &&
player[i].value > card.value){
return player[i];
}
if(matchCase2 === null && player[i].type.type == card.type.type){
matchCase2 = player[i];
}
if(matchCase3 === null && player[i].type.adu === true){
matchCase3 = player[i];
}
}
if(matchCase2 !== null) return matchCase2;
if(matchCase3 !== null) return matchCase3;
return matchCase4;
}
console.log(getNextCard(player2, asztal[0]));
console.log(getNextCard(player3, asztal[0]));
console.log(getNextCard(player4, asztal[0]));

How do I get JavaScript to recognize whether an object is in an array?

New to JavaScript objects. In the code below, I'm able to create and populate a list of book objects that each person has "checked out". However I am unable to "return" the books because I can't get seem to identify which patron's array the book is "checked out" in. I'm using
if (object in array) . . .
I got this from one of the previous answers. The statement block with the if never executes. Thanks for your help!
function Book(title, pub_date, call_number, authors){
this.title = title;
this.availability = true;
this.pub_date = pub_date;
this.current_date = null;
this.check_out_date = null;
this.call_number = call_number;
this.authors = authors;
}
Book.prototype.checkOut = function(){
this.availability = false;
var rdom = (Math.random() * 31 +1).toFixed(0);
var current_date = new Date();
this.check_out_date = new Date(current_date - rdom*24*3600*1000);
}
Book.prototype.checkIn = function(){
this.availability = true;
}
Book.prototype.isOverdue = function(){
var current_date = new Date();
if ((current_date - this.check_out_date)/1000/3600/24 > 14)
return true;
else
return false;
}
function Author(first_name, last_name){
this.first_name = first_name;
this.last_name = last_name;
}
function Patron(firstname, lastname, lib_card){
this.firstname = firstname;
this.lastname = lastname;
this.lib_card = lib_card;
this.books_out = [];
this.fine = 0;
}
Patron.prototype.readBook = function(book){
this.books_out.push(book);
}
Patron.prototype.returnBook = function(book){
this.books_out.pop(book);
}
var redAuthors, blueAuthors, greenAuthors, yellowAuthors, purpleAuthors
var redAuthor1 = new Author('John', 'Smith');
var redAuthor2 = new Author('James', 'Sullivan');
var redAuthors = [redAuthor1, redAuthor2];
var blueAuthors = greenAuthors = yellowAuthors = purpleAuthors = redAuthors;
redBook = new Book('Lakes', 1963, 456789, redAuthors);
blueBook = new Book('Rivers', 1964, 123456, blueAuthors);
greenBook = new Book('Streams', 1965, 234567, greenAuthors);
yellowBook = new Book('Ponds', 1966, 345678, yellowAuthors);
purpleBook = new Book('Brooks', 1967, 567891, purpleAuthors);
var catalog = [redBook, blueBook, greenBook, yellowBook, purpleBook]
var patron1 = new Patron('Sally', 'Hudson', '1');
var patron2 = new Patron('Rachel', 'Hung', '2');
var patron3 = new Patron('Andy', 'Cunningham', '3');
var patron4 = new Patron('Steve', 'Cote', '4');
var patron5 = new Patron ('Ted', 'Mitrou', '5');
var patrons = [patron1, patron2, patron3, patron4, patron5]
for (var day_count = 0; day_count < 10; day_count++){
for (var book_count = 0; book_count < 5; book_count++){
if (catalog[book_count].availability == true){
for (var pat_count = 0; pat_count < 5; pat_count++){
if (patrons[pat_count].books_out.length <= 1){
catalog[book_count].checkOut();
patrons[pat_count].readBook(catalog[book_count]);
break;
}
else
continue;
}
}
else {
catalog[book_count].checkIn();
for (pat_counter = 0; pat_counter < 5; pat_counter++){
if (catalog[book_count] in patrons[pat_counter].books_out){
if (catalog[book_count].isOverdue)
patrons[pat_counter].fine += 5;
patrons[pat_counter].books_out.returnBook(catalog[book_count]);
}
}
}
}
}
for (var k = 0; k < 5; k++){
console.log("Patron: " + patrons[k].firstname + " " + patrons[k].lastname);
console.log("Books checked out: ")
for (l = 0; l < patrons[k].books_out.length; l++) {
console.log(patrons[k].books_out[l].title);
}
console.log("Fine: $" + patrons[k].fine);
console.log();
}
You can use indexOf:
if (array.indexOf(object) > -1)
x in y would only return true if x is a string containing the name of a property on y.

Return more than one values from a function in Javascript using for loop

I am using following code snippet and I am pretty sure I am doing something that wrong that is why it is not returning more than one values. I need experts opinion on it.
function returnValues(testArray)
{
var accountId, orders, abstractOrders, titleOrder;
var childOrders = new Array();
for(var i = 0; i < testArray.length; i++)
{
accountId = typeof testArray[i] === 'undefined'?'':testArray[i].id;
orders = getOrderofParentAccount(accountId);
abstractOrders = abstractOrderYTD(orders);
titleOrder = titleOrderYTD(orders);
childOrders[abstractOrders,titleOrder];
}
return childOrders;
}
You probably want to return an array of objects:
function returnValues(testArray)
{
var accountId, orders, abstractOrders, titleOrder;
var childOrders = new Array();
for(var i = 0; i < testArray.length; i++)
{
accountId = typeof testArray[i] === 'undefined'?'':testArray[i].id;
orders = getOrderofParentAccount(accountId);
abstractOrders = abstractOrderYTD(orders);
titleOrder = titleOrderYTD(orders);
childOrders.push({abstract: abstractOrders,title: titleOrder}); //<-Changed
}
return childOrders;
}
//To retrieve the values
var orders = returnValues(yourarray);
for( var i in orders ){
console.log("====="+i+"======");
console.log('Abstract Orders:');
console.log(orders[i].abstract);
console.log('Title Orders:');
console.log(orders[i].title);
}

How to convert a nested array in javascript to json structure

In the following code i am trying to populate the javascript class,such that i get an object which i can stringify to json string.
function classValue(valuearrs) {
for (var i = 0; i < valuearrs.length; i++) {
for (j = 0; j < valuearrs[i].length; j++) {
this.id = valuearrs[i][j];
this.name = valuearrs[i][j];
this.somekey = valuearrs[i][j];
}
}
}
function CreatenestedarrObj( valuearr) {
this.Arrayparameters = [new classValue (valuearr)];
}
function ArrayMethodCall() {
var valuearr = new Array();
valuearr[0] = "myval1";
valuearr[1] = "myval2";
valuearr[2] = "myval3";
var valuearr1 = new Array();
valuearr1[0] = "myval11";
valuearr1[1] = "myval12";
valuearr1[2] = "myval13";
nestedarr = new Array();
nestedarr[0] = valuearr;
nestedarr[1] = valuearr1;
var x = new CreatenestedarrObj( nestedarr);
var strobject = JSON.stringify(x);
alert(strobject);
}
</script>
</head> <body> MethodCall: <input type="button" value="Call Method" onclick=" ArrayMethodCall ()" />
After Stringifying the value expected is {ArrayParameters:[{myval1,myval2,myval3},{myval1,myval12,myval13}]}.The thing i can think i am missing is creating new object each time in the loop but how ? or i might be totally wrong.Any help will be much appreciated.
try this
function classValue(valuearrs) {
var arr = []
for (var i = 0; i < valuearrs.length; i++) {
for (j = 0; j < valuearrs[i].length; j++) {
var temp = new Object();
temp.id = valuearrs[i][j];
temp.name = valuearrs[i][j];
temp.somekey = valuearrs[i][j];
arr[j] = temp;
}
}
return arr;
}
Change this:
function classValue(valuearrs) {
var arr=[]
for (var i = 0; i < valuearrs.length; i++) {
arr[i]={};
for (j = 0; j < valuearrs[i].length; j++) {
arr[i].id = valuearrs[i][j];
arr[i].name = valuearrs[i][j];
arr[i].somekey = valuearrs[i][j];
}
}
return arr;
}
i don't know why you need to split the nestedarr to id,name and somekey
but if you don't need to, just return the valuearrs and you will be fine:
function classValue(valuearrs) {
return valuearrs;
}
function CreatenestedarrObj( valuearr) {
this.Arrayparameters = [new classValue (valuearr)];
}
function ArrayMethodCall() {
var valuearr = new Array();
valuearr[0] = "myval1";
valuearr[1] = "myval2";
valuearr[2] = "myval3";
var valuearr1 = new Array();
valuearr1[0] = "myval11";
valuearr1[1] = "myval12";
valuearr1[2] = "myval13";
nestedarr = new Array();
nestedarr[0] = valuearr;
nestedarr[1] = valuearr1;
var x = new CreatenestedarrObj( nestedarr);
var strobject = JSON.stringify(x);
console.info(strobject);
}
the output is
{"Arrayparameters":[[["myval1","myval2","myval3"],["myval11","myval12","myval13"]]]}
or far better if you don't want it as Arrayparameters, you can use following code
var strobject = JSON.stringify(nestedarr);
and the output will be like this :
[["myval1","myval2","myval3"],["myval11","myval12","myval13"]]

Categories