0

I have this javascript code which generate a multi array with static values:

var items = [ ["red", "blue"], ["green", "yellow"] ];
console.log(items[1][1]); // green

but now I would like to fill the values dynamically. I tried this:

var items = [[]];
$.each($("input[name='checkboxColors1']:checked"), function(){            
   items[0].push($(this).val());
});

$.each($("input[name='checkboxColors2']:checked"), function(){            
    items[1].push($(this).val());
});

items[0].push... works, but items[1] not

TypeError: items[1] is undefined

Where is my fault?

2
  • 3
    if var items = [[]]; then items[1] is undefined. You can't push into undefined, you need to create the array first. Commented Jan 30, 2019 at 13:03
  • I have wrote you a full working code down below, as an answer, let me know if it works for you Commented Jan 31, 2019 at 19:00

6 Answers 6

2

Javascript is asynchronous... You can't expect two functions to be executed sequentially... :-)

This way can work... But you must initialize your initial array this way:

var items = [ [], [] ];

Since with

var items = [[]];

You only define one internal array inside the external array (items[0]), but you want two (items[0], items[1]).

Sign up to request clarification or add additional context in comments.

6 Comments

Which part of this is asynchronous? It's just looping over the inputs synchronously. And javascript isn't by nature asynchronous. Two functions called in order will execute in order.
The fact that JS is asynchronous has nothing to do with this issue.
@Suxino: you are right, but with the first version of the question it had... :-)
All javascript is asyncronous... the two anonymous functions you define will be executed in undefined order... But, as @Suxino noted, if you populate two difefrent variables (items[0] and items[1]), as you currently do, you can forget about asynchronicity... If, as in the first revision of your question, you populate one single array, you can find an undefined element...
Functions will be executed in the order they are called. If the function is passed as a callback to an async operation then it will be called in the future. It is totally false to say all javascript is asynchronous.
|
2

var items = [[]]; You issue is here.

items[0] is an array. but items[1] is undefined. In order to work you need to define items as [[],[]]

Or to make it more dynamic you could do check before that $.each if the items[1] exists and if not create it

Comments

1

You cannot push into an undefined array, you first need to create the array.

You're code has to look like this:

var items = [[], []];
$.each($("input[name='checkboxColors1']:checked"), function(){            
   items[0].push($(this).val());
});

$.each($("input[name='checkboxColors2']:checked"), function(){            
    items[1].push($(this).val());
});

Then it should work properly.

Comments

0

I think you are confused about "push" function. This function insert a new element on the last position of array.

For example

var items = ["grape"];
items.push("apple"); 
console.log(items); //["grape", "apple"].

Comments

0

The best way to do it by creating a Array object and assign values dynamically. In this way you can also define string key as well.Please see below

var items = new Array();

    items[0] = 1;
    items[1] = 2;
    console.log(items);

//Uncomment above block to test.
var items = new Array();
var items0 = [];
var items1 = [];
$.each($("input[name='checkboxColors1']:checked"), function(){            
   items0 = $(this).val();
});

$.each($("input[name='checkboxColors2']:checked"), function(){            
    items1 = $(this).val();
});
items[0] = items0;
items[1] = items1;

3 Comments

@Mark Meyer just edited my answer now i have shared code snippet of sample code.
@MarkMeyer have you checked?
This is no longer throws an error, but it doesn't do what the OP wants. They want items[0] and items[1] to be arrays, hence the title multidemensional array
0

Be careful when you combine static multi-dimension array, with dynamically adding elements with push.

Try the following code, that is dynamic for the two dimensions.

var checkBoxGroupNames = ['checkboxColors1', 'checkboxColors2'];
var items = [];

var checkedChkBoxes = [];

for (var i = 0; i < checkBoxGroupNames.length; i++) {
    checkedChkBoxes = [];

    $.each($("input[name=" + checkBoxGroupNames[i] + "]:checked"), function(){
        checkedChkBoxes.push($(this).val());
    });

    items.push(checkedChkBoxes);
}

console.log(items); // items now holds the two dimension array

For a cleaner code, you may put the logic that find checked checkboxes per group - in a function.

var checkBoxGroupNames = ['checkboxColors1', 'checkboxColors2'];
var items = [];

$.each(checkBoxGroupNames, function(){
  items.push(GetCheckedChkBoxes(this));
});

console.log(items); // items now holds the two dimension array

function GetCheckedChkBoxes(chkBoxGroupName) {
  checkedChkBoxes = [];

  $.each($("input[name=" + chkBoxGroupName + "]:checked"), function(){
    checkedChkBoxes.push($(this).val());
  });

  return checkedChkBoxes;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.