cjm2671
cjm2671

Reputation: 19466

javascript/jQuery Array concatenation?

I have some simple jQuery code:

var response = Array()
$('.task-list').each(function() {
  response.concat(response,$('#' + this.id).sortable('toArray'));
}
);
console.log(response);

The problem I'm having is that I think I'm using concat improperly- the result is an empty array. When I use array push, it works correctly.

Upvotes: 2

Views: 3645

Answers (2)

aziz punjani
aziz punjani

Reputation: 25776

Concat returns the concatenated array, you want this instead

response = response.concat($('#' + this.id).sortable('toArray'));

Simple example

var a = [1,2]; 
var b = [3,4]; 

a = a.concat( b ); // result is [1,2,3,4] which is correct 

If you do the following

a = a.concat( a , b ); // result is [1, 2, 1, 2, 3, 4] not what you want. 

Upvotes: 3

pimvdb
pimvdb

Reputation: 154828

You have to set response to the newly formed array, as described in the specification. You currently don't use the return value at all.

The specification says that for .concat, the array is not altered, but the new array is returned:

When the concat method is called with zero or more arguments item1, item2, etc., it returns an array containing the array elements of the object followed by the array elements of each argument in order.

Compare with .push, which says the current array is altered, and that something else is returned instead (the new length):

The arguments are appended to the end of the array, in the order in which they appear. The new length of the array is returned as the result of the call.

So:

response = response.concat($('#' + this.id).sortable('toArray'));

Upvotes: 5

Related Questions