根据属性将数组分成大小不同的块

时间:2018-08-11 11:04:40

标签: javascript arrays

我有以下数组

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;
}

但是这只能根据固定大小分割数组。任何形式的建议,我们感激不尽。

谢谢

2 个答案:

答案 0 :(得分:1)

您可以通过检查同一学期的最后一组来简化数组。

var array = [{ semester: 1, name: 'Book1' }, { semester: 1, name: 'Book2' }, { semester: 2, name: 'Book4' }, { semester: 3, name: 'Book5' }, { semester: 3, name: 'Book6' }, { semester: 4, name: 'Book7' }],
    grouped = array.reduce((r, o) => {
        var last = r[r.length - 1];
        if (last && last[0].semester === o.semester) {
            last.push(o);
        } else {
            r.push([o]);
        }
        return r;
    }, []);

console.log(grouped);
.as-console-wrapper { max-height: 100% !important; top: 0; }

答案 1 :(得分:1)

您可以简单地使用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);