js operation object array, judge when there are multiple same attribute values

In the arr array, there are multiple identical groups. I want to calculate how many groups there are in total. When the group number changes, groupNum is incremented by 1, and the group number is added to the array.

var arr = [
    {name: 'a1', group: 1},
    {name: 'b1', group: 1},
    {name: 'c1', group: 1},
    {name: 'd1', group: 1},
    {name: 'a2', group: 2},
    {name: 'b2', group: 2},
    {name: 'c2', group: 2},
    {name: 'd2', group: 2},
    {name: 'a3', group: 3},
    {name: 'b3', group: 3}
];

var newArr = []; // 存放 group 的新数组
var lastGroup= -1; // 上次group 属性值,用来判断
var groupNum = 0; // 一共几组

for (let i = 0; i < arr.length; i++) {
    let group = arr[i].group;
    if (lastGroup != group) {
        newArr.push(group);
        groupNum ++;
        lastGroup = group;
    }
}
console.log(newArr); // [1, 2, 3]
console.log(groupNum); // 3

 

Guess you like

Origin blog.csdn.net/qq_40015157/article/details/113868389