Industrial
Industrial

Reputation: 42788

Jquery array filtering - grep()?

How can I sort an array as the one shown below with jquery's own functions? I assume that grep() is the one that I should be looking at?

Thanks!

The array:

array (

    array(
        'id' => 0,
        'name' => 'myName',
        'weight' => 100  
    );

    array(
        'id' => 1,
        'name' => 'myName2',
        'weight' => 150,
    );

);

Edit: It's a PHP array to clarify things - im not completely sure how to write a proper javascript (JSON?) array?

Upvotes: 1

Views: 1502

Answers (2)

lonesomeday
lonesomeday

Reputation: 237975

First, I'm going to assume that you're actually talking about a Javascript array that looks something like this:

var myArray = [
    {
        id: 0,
        name: 'myName',
        weight: 100
    },
    {
        id: 1,
        name: 'myName2',
        weight: 150
    }
]

You can then call the native Javascript function sort() on this array. In this case, you'll need to provide a function callback. This needs to be defined with the syntax function (a, b). a and b are the elements in your array. You need to return -1 if a should be higher ranked than b in the array, 1 if it should be lower ranked and 0 if they are equal.

If you want to sort them in descending order of weight, you could do the following:

myArray.sort(function(a, b) {
    return b.weight - a.weight;
});

Upvotes: 3

aefxx
aefxx

Reputation: 25279

There's no such method as to sort an array with jQuery. Why don't you just use Array.prototype.sort instead? It's native code and you may pass it a function to compare any of the nested arrays' values.

var myarr = [
    {id: 3, foo: 'bax'},
    {id: 1, foo: 'baz'},
    {id: 2, foo: 'bay'}
];

// Sort by id
myarr = myarr.sort(function(x, y) {
    return x.id >= y.id;
});

Upvotes: 1

Related Questions