{underscore.js}名字按字母顺序排在姓氏之前

时间:2014-04-10 08:33:24

标签: javascript underscore.js

从给定的学生数组中按字母顺序查找姓氏在其姓氏之前的所有学生的方法。 按姓名以降序打印学生。 我必须使用Underscore.js 请帮忙

1 个答案:

答案 0 :(得分:0)

<强> Demo

// Initialize students array.
var students = [ {
    firstname: 'Sachin',
    secondname: 'Tendulkar'
}, {
    firstname: 'Sourav',
    secondname: 'Ganguly'
}, {
    firstname: 'Rahul',
    secondname: 'Dravid'
}, {
    firstname: 'Virat',
    secondname: 'Kohli'
}, {
    firstname: 'Rohit',
    secondname: 'Sharma'
}];

// Filter students whose firstname is before secondname.
var testStudents = _.filter(students, function(student){
    return student.firstname < student.secondname;
});

// Sorted the array in asc order.
testStudents = _.sortBy(testStudents, function(student){
    return student.firstname + ' ' + student.secondname;
});

// Reverse the array.
testStudents = testStudents.reverse();

// Log the result.
console.log(testStudents);