我有很多类似的结构:

student :
 name: SomeName
 city : someSity
 school : someschool
 date : somedate


我想要以某种方式对它们进行排序(带有测试数据):

Sorted_map:
    city : NY
       school: School1
             name:Name1
             name: Name2
             name: Name4
       shool: School2
             name:Name11
             name: Name21
             name: Name41

    city: WDC
        school: School3
           name: Name22
           name: Name29


我所做的是按城市排序:

function groupBy( array , f ) {
    var groups = {};
    array.forEach( function( o )
    {
        var group = JSON.stringify( f(o) );
        groups[group] = groups[group] || [];
        groups[group].push( o );
    });
     return groups;
}


var result = groupBy(sudentsItems, function(item)
    {

        return unifyCity(item.city);
    }


因此,现在仅按“城市”键进行排序。如何在城市内对数据进行排序?

我想我需要类似Map >;

数据样本:

[{
    "name":   "John Some",
    "city":   "NY",
    "school": "NY Central",
    "date":   1460986261733
}, {
    "name":   "Sarah Mil",
    "city":   "Moscow",
    "school": "Moscow Central",
    "date":   1460986201733
}, {
    "name":   "John Again",
    "city":   "NY",
    "school": "NY Central",
    "date":   1460986261733
}, {
    "name":   "Kit Parcer",
    "city":   "NY",
    "school": "NY Central",
    "date":   1460086261733
},  {
    "name":   "Anna Love",
    "city":   "SPB",
    "school": "SPB Central",
    "date":   1460983261733
}]

最佳答案

看起来您正在寻找排序数据还是分组数据。



var data = [{ "name": "John Some", "city": "NY", "school": "NY Central", "date": 1460986261733 }, { "name": "Sarah Mil", "city": "Moscow", "school": "Moscow Central", "date": 1460986201733 }, { "name": "John Again", "city": "NY", "school": "NY Central", "date": 1460986261733 }, { "name": "Kit Parcer", "city": "NY", "school": "NY Central", "date": 1460086261733 }, { "name": "Anna Love", "city": "SPB", "school": "SPB Central", "date": 1460983261733 }],
    object = {};

data.sort(function (a,b) {
    return a.city.localeCompare(b.city) ||
        a.school.localeCompare(b.school) ||
        a.name.localeCompare(b.name);
});

data.forEach(function (a) {
    object[a.city] = object[a.city] || {};
    object[a.city][a.school] = object[a.city][a.school] || [];
    object[a.city][a.school].push(a.name);
});

document.write('<pre>data sorted: ' + JSON.stringify(data, 0, 4) + '</pre>');
document.write('<pre>data grouped: ' + JSON.stringify(object, 0, 4) + '</pre>');

关于javascript - 复杂分类,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/36695259/

10-09 22:10