您的输出看起来很像地图。我会写成:
{
2 : [ 6, 3 ],
1 : [ 1, 2 ],
3 : [ 1 ]
}
要获得该映射,我将遍历数组,提取键和值,然后将值添加到正确的数组中,如果尚未创建,请确保创建它。
var arr = ["2:6", "2:3", "1:1", "1:2", "3:1"];
var map = {};
arr.forEach(function(item){
var split = item.split(':');
if (!map[split[0]]) map[split[0]] = [split[1]];
else map[split[0]].push(split[1]);
});
显然,从我的地图中你可以很容易地得到你想要的数组:
var result = [];
for (var key in map) {
if (map.hasOwnProperty(key)) // best practice
result.push(key+':'+map[key]);
}
console.log(result); // ["1:1,2", "2:6,3", "3:1"]
注意:它的项目顺序与您的顺序不同,但可以通过迭代原始数组以获取键而不是使用 for..in 来轻松解决:
var result = [];
arr.forEach(function(item){
var key = item.split(':')[0];
if (map[key]) {
result.push(key+':'+map[key]);
delete map[key]; // destroys the map!
}
});
console.log(result); // ["2:6,3", "1:1,2", "3:1"]
解决方案 2(无中间图):
此解决方案的复杂度为 O(n^2):
var arr = ["2:6", "2:3", "1:1", "1:2", "3:1"];
var result = [];
for (var i=0; i<arr.length; i++) {
if (!arr[i]) continue;
var key = arr[i].split(':')[0];
var values = [];
for (var j=i; j<arr.length; j++) {
var split = arr[j].split(':');
if (split[0] === key) {
values.push(split[1]);
arr[j] = undefined; // destroys the original array
}
}
result.push(key + ':' + values);
}
console.log(result); // ["2:6,3", "1:1,2", "3:1"]