Xulfee
Xulfee

Reputation: 986

concatenate Array Recursively

I want to merge recursively arrays..

My code is:

var allitemorder;
var itemorder;

$('.divclass').each(function () {
      itemorder = $(this).sortable('toArray');
      allitemorder = $.merge([], itemorder);
});

Kindly help.

Upvotes: 1

Views: 431

Answers (3)

Deefjuh
Deefjuh

Reputation: 159

allitemorder = $.merge([], itemorder); 

Looks like you are resetting allitemorder with itemorder. So shouldn't this be :

allitemorder = $.merge(allitemorder, itemorder); 

EDIT: as Nick states: $.merge(allitemorder, itemorder); suffices (without setting the variable allitemorder again). I would totally go with his shorthand solution.

Upvotes: 1

user113716
user113716

Reputation: 322562

Try this:

var array = $('.divclass').map(function () {
      return $(this).sortable('toArray');
}).get();

Returning an array in .map() automatically merges the array into the jQuery object created. Then .get() retrieves the final array.

Upvotes: 2

Nick Craver
Nick Craver

Reputation: 630559

You need just a slight change, like this:

var allitemorder = [], itemorder;

$('.divclass').each(function () {
    itemorder = $(this).sortable('toArray');
    $.merge(allitemorder, itemorder);
});

Or the shorter:

var allitemorder = [];    
$('.divclass').each(function () {
    $.merge(allitemorder, $(this).sortable('toArray'));
});

$.merge(first, second) takes the elements from the second array and puts them in the first, so you need to pass the array you want to accumulate into as the first argument each time.

Upvotes: 3

Related Questions