is there a function in jquery to order the elements of an array or a json elements or something similar like that?
Thanks.
You are looking for javascript's .sort() method. I know you've asked for a jQuery solution, but I think this is what you are looking for.
You can call .sort() on any array. If you pass it a function, it will treat it as a comparator function. This means you can sort any array, however you want.
If you want to sort (ascending) an array of numbers using a comparator function, you'd do it like so:
arrayVariable.sort(function(a,b) {
return a-b;
});
It doesn't need to be just numbers though. You objects by any criteria:
arrayVariable.sort(function(a,b) {
/* assume a and b are both objects with a "key" property */
return a.key - b-key;
});
This will sort (ascending) the array by the .keys of the objects within the array.
No but there is a way of doing that built into JavaScript:
my_array = [67,2,5,1,90,8];
my_array.sort(function(a,b){return a-b;})
// my_array now contains [1,2,5,8,67,90]
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort
Javascript already has an Array.sort method.
var arr = ["red", "blue", "green"];
arr.sort(); // default sort is lexicographic.
// arr == ["blue", "green", "red"]
If you need a more sophisticated sort, you must use a function argument.
var arr = [101, 90, 200];
arr.sort();
// arr == [101, 200, 90] as the elements are treated as strings.
arr.sort(function(a, b){ return a - b;});
// arr == [90, 101, 200];
return a.key - b.key;