TroyGrosfield.com TroyGrosfield.com

Headline

JQuery Sorting by Attribute Value

Author
by Troy Grosfield
Date
April 25th, 2014
Category
Developer
Story

Since jquery objects are “array-like” and not actual arrays,  things like “sort” raise a few questions after inspecting jquery code.  As of jquery 2.1.0 you notice that “sort” isn’t a document method and diving into the source, you’ll see that it’s for internal use only:

// For internal use only.
// Behaves like an Array's method, not like a jQuery method.
push: push,
sort: arr.sort,
splice: arr.splice

So how do you safely sort an “array” of jquery objects?

Steps

  1. select all object via jquery selector
  2. convert to actual array (not array-like jquery object)
  3. sort the array of objects
  4. convert back to jquery object with the array of dom objects

Html

<div class="item" data-order="2">2</div>
<div class="item" data-order="1">1</div>
<div class="item" data-order="4">4</div>
<div class="item" data-order="3">3</div>

Plain jquery selector

> $('.item')
[
  <div class="item" data-order="2">2</div>,
  <div class="item" data-order="1">1</div>,
  <div class="item" data-order="4">4</div>,
  <div class="item" data-order="3">3</div>
]

Sort this by attribute (assumed to be a numeric value)

function getSorted(selector, attrName) {
    return $($(selector).toArray().sort(function(a, b){
        var aVal = parseInt(a.getAttribute(attrName)),
            bVal = parseInt(b.getAttribute(attrName));
        return aVal - bVal;
    }));
}
> getSorted('.item', 'data-order')
[
  <div class="item" data-order="1">1</div>,
  <div class="item" data-order="2">2</div>,
  <div class="item" data-order="3">3</div>,
  <div class="item" data-order="4">4</div>
]

Now you have a sorted jquery “array-like” object. Hope this helps!

Tags
Comments
No Comments »

No Comments Yet

Leave a reply