0

I don't know how to categorise the type of array that i need. The type of array i require is one which can store 3 different values in a collection.

For Example

var Array = [["John", "Smith", "39"],["Michael", "Angel", "76"]]

Each time i push new data to array in the same format of [Forename, Surname, Age]. How do i declare the array and add data to the array in this format?

Then once in the array retrieve it such as print each collection to console log for example in the following format.

console.log("John" + "Smith" + "39")
console.log("Michael" + "Angel" + "76")
0

2 Answers 2

2

First of all, don't call your variable Array because Array is already a type defined in the ECMAScript standard. Redefining Array may have undefined behavior (read: Very Bad Things). In my example code below, I've renamed it to myArray.

In your example, your array is an array of arrays, i.e. every element is another array. In order to push more data into your top-level array, simply call .push().

myArray.push(["Joe", "Somebody", "43"]);

If you're looking to display a record on the console, you can use a compound index:

var myArray = [["John", "Smith", "39"],["Michael", "Angel", "76"]];
// prints MichaelAngel76
console.log(myArray[1][0] + myArray[1][1] + myArray[1][2])
// prints JohnSmith39
console.log(myArray[0][0] + myArray[0][1] + myArray[0][2])

Or if you want to display every record:

// prints:
// JohnSmith39
// MichaelAngel76
myArray.forEach(function (elem) {
    console.log(elem[0] + elem[1] + elem[2]);
});
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks this was exactly what i needed was having issues with the format specially when it came to retrieving the data from array in that format. :)
2

Array.push(["a", "b", "c" ])

This would work, push allows you to append to an array and you can have a list within the push to create 2d arrays

myObj = Array[0]; //index of required data
console.log(myObj[0] + myObj[1] + myObj[2])

This would then give the data output in the format you want, but would just be a very long string...

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.