原理是使用javascript的sort()函數,此函數也提供讓使用者自訂sort function。
<script type="text/javascript"> var arr = [ { "ID": 135, "Name": "Fargo Chan", "Address": "34, Baker Street" }, { "ID": 432, "Name": "Aaron Luke", "Address": "BLDG 1, J Street" }, { "ID": 252, "Name": "Dilip Singh", "Address": "Hotel J, SE" } ]; // Before Sorting document.write("<b>Before Sorting </b><br/>"); for (var n = 0; n < arr.length; n++) { document.write(arr[n].ID + ' ' + arr[n].Name + '<br>'); } // ascending order function SortByID(x,y) { return x.ID - y.ID; } function SortByName(x,y) { return ((x.Name == y.Name) ? 0 : ((x.Name > y.Name) ? 1 : -1 )); } // Call Sort By Name arr.sort(SortByName); document.write("<br/><b>After Sorting </b> <br/>"); for(var n=0;n<arr.length;n++){ document.write(arr[n].ID + ' ' + arr[n].Name + '<br>'); } </script>
可重覆使用的範例:參考至How to sort a JSON array ?
Here's a more flexible version, which allows you to create reusable sort functions, and sort by any field
var sort_by = function(field, reverse, primer){ reverse = (reverse) ? -1 : 1; return function(a,b){ a = a[field]; b = b[field]; if (typeof(primer) != 'undefined'){ a = primer(a); b = primer(b); } if (a<b) return reverse * -1; if (a>b) return reverse * 1; return 0; } }
Now you can sort by any field at will
// Sort by price high to low homes.sort(sort_by('price', true, parseInt)); // Sort by city, case-insensitive, A-Z homes.sort(sort_by('city', false, function(a){return a.toUpperCase()}));
可以改寫成jQuery plugin的寫法:
(function($) { $.extend({ sortBy : function(objects, field, reverse, fieldValueFunc) { //ASC or DESC //if reverse is true, data will be sorted using DESC reverse = (reverse) ? -1 : 1; //init sort func var sortFunc = function(elA, elB) { //get value by field name elA = elA[field]; elB = elB[field]; if (typeof (fieldValueFunc) != 'undefined') { elA = fieldValueFunc(elA); elB = fieldValueFunc(elB); } //return element comparison value if (elA < elB) return reverse * -1; if (elA > elB) return reverse * 1; return 0; }; //call sort() method using sortFunc objects.sort(sortFunc); } }); })(jQuery);
使用方式
$.sortBy(arr,"ID",false,parseInt);
沒有留言:
張貼留言
留個話吧:)