tags:

views:

44

answers:

3

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.

+1  A: 
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.

Deefjuh
+2  A: 

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.

Nick Craver
I like the shorthand version.
Deefjuh
+2  A: 

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.

patrick dw
This would return an array of arrays ;)
Nick Craver
@Nick - I'm pretty sure that when `.map()` receives and array, it automatically merges it into the jQuery object array. On one occasion where I actually *wanted* an array of arrays, I found that I ended up with only one array.
patrick dw
@patrick - Whoa you're right, that's a bug in core IMO, it shouldn't do a concat, that's an improper handling of returned Arrays specifically. I've never tried this either but that's definitely not the expected result. +1 for this, though I'm actually *hoping* it breaks in a future version, no offense :)
Nick Craver
@Nick - None taken. :o) I suppose it assumes it's getting an array of DOM elements or something, and therefore wants to concat. It certainly was unexpected when I came across it.
patrick dw