Skip to content

Latest commit

 

History

History
120 lines (102 loc) · 2.41 KB

有关数据分组的两种实现思路.md

File metadata and controls

120 lines (102 loc) · 2.41 KB

问题与需求

一个 JSONArray 结构的数据,基于其中某个相同的属性值进行归类摆放。

示例数据

// JavaScript
var list = [{
        "name": "John",
        "Average": 15,
        "High": 10,
        "DtmStamp": 1358226000000
    },
    {
        "name": "Jane",
        "Average": 16,
        "High": 92,
        "DtmStamp": 1358226000000
    },
    {
        "name": "Jane",
        "Average": 17,
        "High": 45,
        "DtmStamp": 1358226000000
    },
    {
        "name": "John",
        "Average": 18,
        "High": 87,
        "DtmStamp": 1358226000000
    },
    {
        "name": "Jane",
        "Average": 15,
        "High": 10,
        "DtmStamp": 1358226060000
    },
    {
        "name": "John",
        "Average": 16,
        "High": 87,
        "DtmStamp": 1358226060000
    },
    {
        "name": "John",
        "Average": 17,
        "High": 45,
        "DtmStamp": 1358226060000
    },
    {
        "name": "Jane",
        "Average": 18,
        "High": 92,
        "DtmStamp": 1358226060000
    },
    {
        "name": "Bob",
        "Average": 18,
        "High": 91,
        "DtmStamp": 1358226060000
    }
];

实现方式一

通过 Map 表的方式来存储相同属性值的数据,以实现数据的归类

// JavaScript
function byGrouping(dataSource, key) {
    var maps = {};
    var key = key || '';
    var result = [];

    if (!key) return dataSource;
    for (var i = 0; i < dataSource.length; i++) {
        var item = dataSource[i];
        if (maps[item[key]]) {
            maps[item[key]].push(item);
        } else {
            maps[item[key]] = [item];
        }
    }

    for (var k in maps) {
        result = result.concat(maps[k]);
    }

    return result;

}

byGrouping(list, 'name');

实现方式二

通过数组排序方法来判断属性值的大小,那么相同属性值就会自动归类在一起

为了优化性能,这里只对不同属性值的数据进行排序判断。

// JavaScript

function bySortGrouping(dataSource, key) {
    var newDataSource = [...dataSource];
    return newDataSource.sort((a, b) => {
        if (a[key] !== b[key]) {
            return a[key].localeCompare(b[key]);
        } else {
            return 0;
        }
    });
}

PS : 此种方式的性能要略低与第一种,并且预测使用的场景也会有有限(预估排序会对原始数据的展示有影响)。