最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Sort the contained objects in an Array by the last name, first name - descending - Stack Overflow

programmeradmin4浏览0评论

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.

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论