按时差对javascript数组进行分组

时间:2015-01-13 04:26:15

标签: javascript jquery arrays

示例输入:

var Player = [
    {
        name: "John",
        Events: {
            timeList: ["7:00 AM", "9:00 AM", "12:01 PM", "2:00 PM"]
        },
        groups: {}
    },
    {
        name: "Doe",
        Events: {
            timeList: ["7:00 AM", "8:00 AM", "10:00 AM", "12:01 PM"]
        },
        groups: {}
    }
];

我试图循环遍历每个玩家的timeList数组,并将该数组中的每个项目分组,它们之间的时差不到2小时。

我尝试循环遍历数组中的每个元素并编写if条件以查看哪些元素匹配。但是,我无法将分组元素推送到单独的数组中。

预期输出:

Player = [
    {
        name: "John",
        Events: {
            timeList: ["7:00 AM", "9:00 AM", "12:01 PM", "2:00 PM"]
        },
        groups: {0: ["7:00 AM", "9:00 AM"], 1: ["12:01 PM", "2:00 PM"]}
    },
    {
        name: "Doe",
        Events: {
            timeList: ["7:00 AM", "8:00 AM", "9:00 AM", "12:01 PM"]
        },
        groups: {0: ["7:00 AM", "8:00 AM", "9:00 AM"], 1: ["12:01 PM"]}
    }
];

如果需要,可以更改对象的结构。

提前一吨。

1 个答案:

答案 0 :(得分:0)

编写一个函数来标准化你的时间,编写一个函数来比较一个时间与它给出的前一个时间(-Infinity的初始条件),循环遍历 Arrays

function timeInMin(str) {
    str = str.split(/[: ]/);
    if (str[0] === '12') {
        if (str[2] === 'AM') {
            str[1] = 0;
        }
    } else if (str[2] === 'PM') {
        str[0] = (+str[0]) + 12;
    }
    return 60 * (+str[0]) + (+str[1]);
}

function groupFactory(groups) {
    var i = -1, last = -Infinity;
    groups = groups || {};
    return function addToGroup(time) {
        var mins = timeInMin(time);
        if (mins - last <= 2 * 60) {
            groups[i].push(time);
        } else {
            ++i;
            groups[i] = [time];
        }
        last = mins;
        return groups;
    };
}

var i, j, gf;
for (i = 0; i < Player.length; ++i) {
    gf = groupFactory(Player[i].groups);
    for (j = 0; j < Player[i].Events.timeList.length; ++j) {
        gf(Player[i].Events.timeList[j]);
    }
}

结果

[
    {
        "name": "John",
        "Events": {
            "timeList": ["7:00 AM", "9:00 AM", "12:01 PM", "2:00 PM"]
        },
        "groups": {
            "0": ["7:00 AM", "9:00 AM"],
            "1": ["12:01 PM","2:00 PM"]
        }
    },
    {
        "name": "Doe",
        "Events": {
            "timeList": ["7:00 AM", "8:00 AM", "10:00 AM", "12:01 PM"]
        },
        "groups": {
            "0": ["7:00 AM", "8:00 AM", "10:00 AM"],
            "1": ["12:01 PM"]
        }
    }
]