Skip to content Skip to sidebar Skip to footer

Complex JQuery Div Sorting

I'm trying to sort some DIVS in different ways and I'm quite lost. I've been trying some stuff but I don't see how to get it to work. I have a set of different divs with the same c

Solution 1:

An interesting method to sort would be to create an array of crafted strings that contain the sorted attribute value, a sperarator and the element's ID.

In your example data the string array should look like:

['Name One#div541', 'Name Two#div354', 'Name Three#div763', ...]

or if you want to sort by the numeric value:

['0001234#div541', '0004321#div354', '0112233#div763', ...]

Note that in that case you should pad the number strings with zeros so the sort by string will be correct.

After that you can simply use the javascript .sort() method on the array. After the array is sorted you can take the IDs by parsing out the data before the delimiter.

If you want the sorting to be in descending order, just use .reverse() after sorting.

Edit

You can convert the crafted array to your desired IDs array like this:

var idsArray = $.map( craftedArray, function(val, i) {
  return val.substring(val.indexOf('#'));
});

Post a Comment for "Complex JQuery Div Sorting"