11

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?

3 Answers 3

16

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 );
Sign up to request clarification or add additional context in comments.

5 Comments

Uhm, console.log(newArray) now returns 4 =/
@David - You sure about that? jsfiddle.net/XLVxw/1 4 would be the appropriate Array length property value.
@David - Oh, I see what you're doing. The .push() method modifies the original array, and returns the new length. That's why your newArray variable shows 4.
yup I'm fairly certain =b And, seriously, thanks for the forDummies() jsfiddle demo. It was needed =) +1, and accepted!
@David - You're welcome! I should have paid more attention to the code in your question in the first place. :o)
2

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']]);

1 Comment

Correct me if I'm wrong, but I think that would give OP the same result that $.merge was giving. I think you would need to do cString.concat([['4','Stackoverflow','stackoverflow.com']]) instead.?
2

you can use merge function like this

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.