我有以下数组

var array=[{ semster:1, name:Book1 }, { semster:1, name:Book2 }, { semster:2, name:Book4 }, { semster:3, name:Book5 }, { semster:3, name:Book6 }, { semster:4, name:Book7 }]


现在,我想对数组进行排序,以将当前数组拆分为数组块,如下所示

var array=[[{ semster:1, name:Book1 }, { semster:1, name:Book2 }],[ { semster:2, name:Book4 }], [{ semster:3, name:Book5 }, { semster:3, name:Book6 }], [{ semster:4, name:Book7 }]]


我试图通过以下代码实现这一目标:

function splitIntoSubArray(arr, count) {
  var newArray = [];
  while (arr.length > 0) {
    newArray.push(arr.splice(0, count));
  }
  return newArray;
}


但这只能在固定大小的基础上划分数组。任何形式的建议,我们将不胜感激。

谢谢

最佳答案

您可以简单地使用Array.reduce()按学期对项目进行分组。地图上的Object.values()为您提供所需的结果。



var array=[{ semster:1, name:"Book1" }, { semster:1, name:"Book2" }, { semster:2, name:"Book4" }, { semster:3, name:"Book5" }, { semster:3, name:"Book6" }, { semster:4, name:"Book7" }];

var result = Object.values(array.reduce((a, curr)=>{
  (a[curr.semster] = a[curr.semster] || []).push(curr);
  return a;
},{}));

console.log(result);

07-28 07:00