根据值的更改时间将数组拆分为更小的数组

时间:2017-06-21 11:37:35

标签: javascript arrays ecmascript-6

还有其他几个问题,但对于所有这个问题,排序键是已知的。

所以这是我的问题。 考虑这个测试类:

class Test{
    constructor(){
        this.value1 = val1;
        this.value2 = val2;
        this.value3 = val3;
    }

这是比较函数

function compare(a,b){
    if(a.value3 < b.value3){
        return -1;
    if(a.value3 > b.value3){
        return 1;
    return 0
}

所以当我有一个array of Test's f.e。与size 50 我会像这样排序这个数组。

arrayOfTest.sort(compare)

将返回按value3排序的数组。现在我想将这个大数组分成几个较小的数组,具体取决于WHEN值3的变化。 例如:

arrayOfTest=[a = Test(value3 = 3),b = Test(value3 = 3),c = Test(value3 = 4)]

应该分成

array1 = [a = Test(value3 = 3),b = Test(value3 = 3)]

array3 = [c = Test(value3 = 4)]

1 个答案:

答案 0 :(得分:1)

在单次传递中实现目标的一种可能方式(无需先排序)将按给定键进行分组,如下面的代码段所示:

var groupBy = function(xs, key) {
  return xs.reduce(function(rv, x) {
    (rv[x[key]] = rv[x[key]] || []).push(x);
    return rv;
  }, {});
};
// groupBy(arrayOfTest, 'value3')