还有其他几个类似的问题,但对于所有这些问题,排序键都是已知的。
所以这是我的问题。 考虑这个测试类:
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
}
所以当我有一个 Test 数组
f.e. 尺码 50
我会像这样对这个数组进行排序。
arrayOfTest.sort(compare)
这将返回按value3
排序的数组。现在我想根据 value3 的变化将这个大数组分成几个较小的数组。
例如:
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)]
最佳答案
一次性实现目标(无需先排序)的一种可能方法是按给定键进行分组,如以下代码片段所示:
var groupBy = function(xs, key) {
return xs.reduce(function(rv, x) {
(rv[x[key]] = rv[x[key]] || []).push(x);
return rv;
}, {});
};
// groupBy(arrayOfTest, 'value3')
关于javascript - 根据值更改的时间将数组拆分为更小的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44675017/