fly*_*gge 5 javascript arrays sorting
我有一个像这样的对象数组(按类型排序,相同类型的对象是相同的):
[
{ "type":"A", "height":50, "width":80 },
{ "type":"A", "height":50, "width":80 },
{ "type":"B", "height":20, "width":100 },
{ "type":"B", "height":20, "width":100 },
{ "type":"C", "height":90, "width":10 }
]
Run Code Online (Sandbox Code Playgroud)
我希望将所有这些对象放在一个数组中,该数组通过交替使用每种类型的对象来排序:
[
{ "type":"A", "height":50, "width":80 },
{ "type":"B", "height":20, "width":100 },
{ "type":"C", "height":90, "width":10 },
{ "type":"A", "height":50, "width":80 },
{ "type":"B", "height":20, "width":100 }
]
Run Code Online (Sandbox Code Playgroud)
这是我的尝试。它不是最有效的,但只要输入不是太大,它应该可以很好地应对。
它假定类型始终是字符串,但并不假定它们始终是 A、B 和 C。它循环输入数据以确定类型并将匹配的类型收集在一起作为“分区”。一旦完成,它就会循环遍历每个分区中依次移动条目的类型,直到完成。如果分区具有不同数量的条目,这没有问题,但转移不存在的对象会浪费时间。
您提到每种类型的对象都是相同的,但我没有考虑到这个细节。如果“相同”指的是“同一对象”(即obj1 === obj2),那么您可能可以利用它来跟踪计数而不是创建所有这些分区数组。
var input = [
{ "type":"A", "height":50, "width":80 },
{ "type":"A", "height":50, "width":80 },
{ "type":"B", "height":20, "width":100 },
{ "type":"B", "height":20, "width":100 },
{ "type":"C", "height":90, "width":10 }
];
var types = [];
var partitions = {};
input.forEach(function(row) {
var type = row.type;
if (partitions[type]) {
partitions[type].push(row);
}
else {
partitions[type] = [row];
types.push(type);
}
});
var output = [];
while (output.length < input.length) {
types.forEach(function(type) {
var next = partitions[type].shift();
if (next) {
output.push(next);
}
});
}
console.log(output);Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
83 次 |
| 最近记录: |