Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I add an array to an array of arrays using jQuery?

I have an array, as below:

var cString =   [
            ['1','Techdirt','www.techdirt.com'],
            ['2','Slashdot','slashdot.org'],
            ['3','Wired','wired.com']
            ];

to this array I want to add another in the same format:

var test = ['4','Stackoverflow','stackoverflow.com']

I've tried using:

var newArray = $.merge(cString, test);

But console.log(newArray); outputs:

[►Array,►Array,►Array,'4','Stackoverflow','stackoverflow.com']

So I'm assuming that I'm missing something obvious. Or attempting something stupid...help?

like image 481
David Thomas Avatar asked Sep 11 '10 17:09

David Thomas


People also ask

How do you add an array to an array of arrays?

To append one array to another, call the concat() method on the first array, passing it the second array as a parameter, e.g. const arr3 = arr1. concat(arr2) . The concat method will merge the two arrays and will return a new array. Copied!

How do you add one array to another array?

Use the concat function, like so: var arrayA = [1, 2]; var arrayB = [3, 4]; var newArray = arrayA. concat(arrayB); The value of newArray will be [1, 2, 3, 4] ( arrayA and arrayB remain unchanged; concat creates and returns a new array for the result).

Can I put an array in an array JavaScript?

An array is an ordered collection of values: each value is called an element, and each element has a numeric position in the array, known as its index. JavaScript lets us create arrays inside array called Nested Arrays. Nested Arrays have one or many arrays as the element of an array.


2 Answers

In addition to push as described by patrick, if you want to create a new list rather than changing the old, you can add arrays together with Array#concat:

var newArray= cString.concat([['4','Stackoverflow','stackoverflow.com']]);
like image 116
bobince Avatar answered Nov 02 '22 14:11

bobince


jQuery is not needed for this. Just use the Array's .push() method to add it to the main array.

var test = ['4','Stackoverflow','stackoverflow.com']

cString.push( test );

What $.merge() does is it walks through the second array you pass it and copies its items one by one into the first.


EDIT:

If you didn't want to modify the original array, you could make a copy of it first, and .push() the new Array into the copy.

var cString =   [
            ['1','Techdirt','www.techdirt.com'],
            ['2','Slashdot','slashdot.org'],
            ['3','Wired','wired.com']
            ];

var test = ['4','Stackoverflow','stackoverflow.com']

var newArray = cString.slice();

newArray.push( test );
like image 38
user113716 Avatar answered Nov 02 '22 15:11

user113716