1 回答
TA贡献1872条经验 获得超3个赞
你可以
将对象分组
level
,level
Clause
为每个和Concatenator
不同的数组收集通过迭代分组对象来重建一个新数组
使用变量
i
来获得交替types
。
var array = [{ type: "Concatenator", level: 3 }, { type: "Clause", level: 4 }, { type: "Clause", level: 1 }, { type: "Concatenator", level: 1 }, { type: "Clause", level: 3 }, { type: "Clause", level: 4 }, { type: "Clause", level: 3 }, { type: "Concatenator", level: 4 }, { type: "Clause", level: 2 }, { type: "Concatenator", level: 2 }, { type: "Concatenator", level: 3 }, { type: "Clause", level: 2 }, { type: "Concatenator", level: 4 }],
order = { Clause: 0, Concatenator: 1 },
temp = array.reduce((r, o) => {
r[o.level] = r[o.level] || [[], []];
r[o.level][order[o.type]].push(o);
return r;
}, {}),
i = 0,
result = Object
.keys(temp)
.sort((a, b) => a - b)
.flatMap(k => {
var r = [];
while (temp[k][i].length) {
r.push(temp[k][i].shift());
i = 1 - i;
}
return r;
});
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
添加回答
举报