0

is there a function in jquery to order the elements of an array or a json elements or something similar like that?

Thanks.

4
  • How do you want elements sorted? This may help: davidwalsh.name/array-sort Commented Jun 16, 2013 at 23:54
  • 1
    Search here: [google.de/search?q=javascript+array+sort][1] Commented Jun 16, 2013 at 23:54
  • thanks to both answers... the sorted must be from keys of each array elements. Commented Jun 16, 2013 at 23:59
  • Both those answers have what you need. The .sort method allows you to define your own sort. All you have to do is return the comparison. say... return a.key - b.key; Commented Jun 17, 2013 at 0:02

3 Answers 3

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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

2 Comments

great, thanks... but how can i order it in an associative array by it's keys?
I don't understand the question. JavaScript doesn't have associative arrays. The analogous thing to PHP associative arrays in JS is objects. Objects don't have orders. What is it you are trying to do?
0

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];

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.