0

I have an array of arrays and I want to be able to add values to the array every time a user hits the add button.

var transactions = [];
transactions[0] = []; // holds date
transactions[1] = []; // holds transaction type
transactions[2] = []; // holds amount


transactions[0][i] = $("date").value;
transactions[1][i] = $("transType").value;
transactions[2][i] = parseFloat( $("amount").value);

these are the snippets . . . I realize I need to work on validation (which I will do) at this point I'm more concerned with loading the arrays. The problem is the method I'm familiar with works with 1-dimensional arrays and I don't know how to replace it.

in short is it possible to reproduce this:

transactions[transactions.length] = $("date").value;

for a multidimensional array.

Thank You

1
  • disregard the [i] that was an attempt using a counter Commented Mar 1, 2013 at 21:16

5 Answers 5

1

Use push:

transactions[0].push( $("date").value );
Sign up to request clarification or add additional context in comments.

Comments

1

You're looking for the Array.push() method. It allows you to push values on to the end of an array.

For your use case, you can do that on both levels of the array. See below:

var transactions = [];
transactions.push([]);
transactions.push([]);

transactions[0].push( $('date').value );

Comments

1

There is no problem for using the same approach:

transactions[0][transactions[0].length] = $("date").value;

or with push method:

transactions[0].push($("date").value);

... keeping in mind that you've initialized transactions[0] with empty array [].

Comments

0

Yes, just idem for multidimensional

transactions[0][transactions[0].length] = var1;

Comments

0

Seems a little weird you are doing:

[[array of transaction dates],[array of transaction types],[array of transaction amounts]]

Are you sure you don't want

[array of transactions, with date,type,amount properties]

?

var transactions = [];
transactions.push({'date': $("date").value, 'type': $("transType").value, 'amount': parseFloat( $("amount").value)});

var i = 0;

alert('date ' + transactions[i].date + ' type ' + transactions[i].type + ' amount ' + transactions[i].amount);

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.