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
2 Answers
Reset to default 9In 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.
本文标签:
版权声明:本文标题:javascript - Sort the contained objects in an Array by the last name, first name - descending - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742213405a2434128.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论