# 如何把数组內 特定元素放到第一个

222 次浏览

``````var qq = [

{
"group": 100,
"info": {"event": 123},
"main": true,
},
{
"group": 100,
"info": {"event": 323},
"main": true,
"sp": 1
},
{
"group": 103,
"info": {"event": 123},
"main": true,
"sp": 13,
},
{
"group": 103,
"info": {"event": 323},
"main": true,
"sp": 10
},
{
"group": 103,
"info": {"event": 123},
"main": true,
"sp": 1
}
];

``````

group是同数字表示是一组的，

``````var qq = [
{
"group": 100,
"info": {"event": 323},
"main": false,
"sp": 1
},
{
"group": 100,
"info": {"event": 123},
"main": true,
},
{
"group": 103,
"info": {"event": 123},
"main": false,
"sp": 1
},
{
"group": 103,
"info": {"event": 123},
"main": true,
"sp": 13,
},
{
"group": 103,
"info": {"event": 323},
"main": true,
"sp": 10
}
];``````
GOGOGO 72
2019-01-12 提问
3 个回答

``````var group, index = -1;
for (var i = 0; i < qq.length; i++) {
var obj = qq[i];
if (group !== obj.group) index = i;
if (obj.sp === 1 && obj.group === group) {
obj.main = false;
qq.splice(i, 1);
qq.splice(index, 0, obj);
}
group = obj.group;
}
console.log(qq);``````
``````qq
.sort((a, b) => a.group !== b.group
? a.group - b.group
: a.sp === 1 ? -1 : 1
)
.forEach(x => x.main = x.sp === 1 ? false : x.main)``````