gpt4 book ai didi

javascript - 如何按各自的组号对数组中的对象进行分组

转载 作者:行者123 更新时间:2023-12-02 23:45:44 34 4
gpt4 key购买 nike

我已经对数组列表进行了排序,并按各自的组号按顺序排列,但我需要对其进行分组(比方说由领导者和他/她的成员)。我想要有额外的字段,如果对象没有相同的组号,它将自动标记为领导者,因此,如果对象具有相同的组号,序列中的第一个对象将被标记为领导者和其他人将自动标记为成员(member)。

THIS IS MY CODE FOR SORTING MY ARRAY LIST AND IT'S CONSOLE/OUTPUT.

$scope.sortedTopAgent = [];
var c = 0;
var sortTopAgentByGroup = function () {
for (const [index, value] of accountArray.entries()) {
for (const [index2, value2] of TeamArray.entries()) {
if (value2.accountname == value) {
c = c + 1;

$scope.sortedTopAgent.push(value2);

$scope.sortedTopAgent.sort(function (a, b) {
return a.groupNo - b.groupNo;
});
console.log($scope.sortedTopAgent)

//console >>

[{
"name": "John",
"groupNo": 1
},
{
"name": "Chelsea",
"groupNo": 1
},
{
"name": "Mark",
"groupNo": 1
},
{
"name": "Peter",
"groupNo": 5
},
{
"name": "Arya",
"groupNo": 5
},
{
"name": "Robert",
"groupNo": 7
},
{
"name": "Mary",
"groupNo": 8
}
]
// end of console
}
}
}

};

我想要一个如下所示的数组:

[{
"name": "John",
"groupNo": 1,
"leaderNo": 1,
"memberNo": ""
},
{
"name": "Chelsea",
"groupNo": 1,
"leaderNo": "",
"memberNo": 1
},
{
"name": "Mark",
"groupNo": 1,
"leaderNo": "",
"memberNo": 1
},
{
"name": "Peter",
"groupNo": 5,
"leaderNo": 2,
"memberNo": ""
},
{
"name": "Arya",
"groupNo": 5,
"leaderNo": "",
"memberNo": 2
},
{
"name": "Robert",
"groupNo": 7,
"leaderNo": 3,
"memberNo": ""
},
{
"name": "Mary",
"groupNo": 8,
"leaderNo": 4,
"memberNo": ""
}
]

最佳答案

您可以使用 Array#map有办法知道是否已经找到领导者。

在这里,我使用 Array#map 的第二个参数作为一个 Set,它最终成为 map 回调函数内的 this 值。如果需要,我使用 size 属性来确定 leaderNo/groupNo

您可以选择任何方便的方式。

const data = [{
"name": "John",
"groupNo": 1
},
{
"name": "Chelsea",
"groupNo": 1
},
{
"name": "Mark",
"groupNo": 1
},
{
"name": "Peter",
"groupNo": 5
},
{
"name": "Arya",
"groupNo": 5
},
{
"name": "Robert",
"groupNo": 7
},
{
"name": "Mary",
"groupNo": 8
}
];

const output = data.map(function(member) {
if (this.has(member.groupNo)) {
// Member
return {
...member,
"leaderNo": "",
"memberNo": this.size
}
}
// Leader
this.add(member.groupNo)
return {
...member,
"leaderNo": this.size,
"memberNo": ""
}
}, new Set())

console.log(output);

关于javascript - 如何按各自的组号对数组中的对象进行分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55860080/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com