admin管理员组

文章数量:1326447

Given the following Array, how do we write code that sorts the contained objects by the last name, first name descending?

[
{key: 1, firstName: "George", lastName: "Jones"},
{key: 1, firstName: "Alison", lastName: "Clarke"},
{key: 1, firstName: "Ben", lastName: "Smith"},
{key: 1, firstName: "Xavier", lastName: "Clark"},
{key: 1, firstName: "Harold", lastName: "Timmins"}
]

I don't know how to proceed on this and I thought you guys might help.

Thanks

Given the following Array, how do we write code that sorts the contained objects by the last name, first name descending?

[
{key: 1, firstName: "George", lastName: "Jones"},
{key: 1, firstName: "Alison", lastName: "Clarke"},
{key: 1, firstName: "Ben", lastName: "Smith"},
{key: 1, firstName: "Xavier", lastName: "Clark"},
{key: 1, firstName: "Harold", lastName: "Timmins"}
]

I don't know how to proceed on this and I thought you guys might help.

Thanks

Share Improve this question edited Oct 20, 2015 at 13:14 YashG99 asked Jun 3, 2013 at 23:40 YashG99YashG99 5291 gold badge10 silver badges20 bronze badges 2
  • 3 This looks more like JavaScript to me... – MadProgrammer Commented Jun 3, 2013 at 23:41
  • Please, Java is not JavaScript. Edit your question accordingly to get the desired answer. – Luiggi Mendoza Commented Jun 3, 2013 at 23:45
Add a ment  | 

2 Answers 2

Reset to default 9

In JavaScript:

myarray.sort(function(a, b) {
    return b.lastName.localeCompare(a.lastName) ||
           b.firstName.localeCompare(a.firstName)
});

DEMO: http://jsfiddle/nMs67/

Write your own Comparator that pares the objects using the logic you wrote above, and call the two parameters version of Arrays.sort with it.

This is largely the same in Java or JavaScript, except that in Java, the Comparator needs to be an object of a class implementing the Comparator interface, while in JavaScript just a function would be enough. This somewhat highlights JavaScript's functional aspect and Java's Object oriented nature.

本文标签: