Reputation: 85
I have an array that is structured like this.
Object
(
[11065] => Object
(
[firtname] => Linda
[lastname] => Bell
[fullname] => Bell, Linda
)
[11110] => Object
(
[firstname] => Andrew
[lastname] => Smith
[fullname] => Andrew, Smith
)
[11279] => Object
(
[firstname] => Sabrina
[lastname] => Wu
[fullname] => Sabrina Wu
)
)
As you can see the array is current being sorted by the persons id given by [11065],[11110],[11279]
Is there a way to sort this array by person's lastname in JavaScript or jQuery?
Upvotes: 1
Views: 551
Reputation: 925
Use a compareFunction with Array.sort(compareFunction). To do that, you need the containing object to be an Array, so you probably want to do something like:
var a = [{id: 11065,
firstname: "Linda",
lastname: "Bell"},
{id: 11279,
firstname: "Sabrina",
lastname: "Wu"},
{id: 11110,
firstname: "Andrew",
lastname: "Smith"}
];
a.sort(function (a, b) { if (a.lastname > b.lastname) {
return 1;
} else if (a.lastname < b.lastname) {
return -1;
} else {
return 0;
}});
console.log(a);
Upvotes: 2
Reputation: 25421
Arrays are Objects. Try this:
Array.prototype.sort.call(yourObject, function(x, y) {
return x.lastName > y.lastName;
});
I'd take lonesomeday's advice though and use an actual Array.
Do your keys mean something? I'd make them a property of your objects inside your array.
Upvotes: 0
Reputation: 238045
You are using an object, not an array. Arrays are a special kind of object with sequentially named properties and certain special properties and methods to help access them.
Javascript object properties are not sorted in any particular order. According to the specification, there is no defined order; most browsers will use the order in which properties are defined. You should neither rely on any particular order nor expect to change it.
If you want an ordered collection, you'll need an array.
Upvotes: 1
Reputation: 7096
var data = [
{ name:"nate"},
{name:"john"},
{name:"paul"}
];
data.sort(function(a, b) {
return a.name > b.name;
});
Upvotes: 0
Reputation: 8197
If I'm not mistaken, you can pass a compare function to the array.sort method. (which if I'm not mistaken does not exist in all browsers). I'm sure they have something around somewhere. jQuery has a sort that takes a function for sure.
Anyway, you would make a function to compare your objects based on last name rather than that id.
Array.sort( function ( a, b ) {
if (a.lastname < b.lastname) return -1;
if (a.lastname > b.lastname) return 1;
return 0;
});
Expanded upon Mimisbrunnr's example.
Upvotes: 0
Reputation: 32524
Array.sort
takes a functional argument with which it compares values.
Array.sort( function ( a, b ) {
if (a < b) return -1;
if (a > b) return 1;
return 0;
});
Upvotes: 0