我有大量的数字数组:
[1, 2, 3, 4, 20, 20, 20, 35, 34, 60, 60, 61, 62]
我正在寻找一个可以对这些数字进行分组的函数,以便该函数的输出为:
1-4
、20
、34-35
、60-62
,如果我指定要将 4 个组传递给函数。
我有时间,所以我自己尝试了一下。下面是一个示例。我使用了一个集合来防止重复。我所做的是
1. sort the array
2. construct a set
3. loop through all elements
3a. if first is assigned then
3a1. check first + 1 !== current el then
3a1_1. add to set, init first and reset step
3a2. else incr step
3b. else init current el as first
4. convert set to array
const a = [1,2,3,4,20,20,20, 35, 34, 60, 60, 61, 62];
// sort the numbers
const b = a.sort((el1, el2) => el1 - el2);
// use a set to prevent duplicates
const result = new Set();
let first, step = 1;
// loop through all els
for(let i = 0; i < b.length; ++i) {
if (first) {
if (first+step !== b[i]) {
result.add( (step === 1 ? first : first + '-' + b[i-1]) );
first = b[i];
step = 1;
}
else ++step;
}
else first = b[i];
}
console.log('before', a);
console.log('after', [...result]); // TADA !
.as-console-wrapper { max-height: 100% !important; top: 0; }
首先,您可以对给定数组进行排序并检查实际值是否与前置数组相同,然后退出循环。否则,检查该值是否是真正的前置值,然后为最后一个数组分配该值,如果不是,则将新数组推送到结果集。
要获得组合结果,请映射连接的数组。
var data = [1, 2, 3, 4, 20, 20, 20, 35, 34, 60, 60, 61, 62].sort(function (a, b) { return a - b; }),
groups = data.reduce(function (r, a, i, aa) {
var last = r[r.length - 1] || [];
if (last[last.length - 1] === a) {
return r;
}
if (!i || last[last.length - 1] + 1 !== a) {
r.push([a]);
} else {
last[1] = a;
}
return r;
}, []).map(function (a) {
return a.join('-');
});
console.log(groups);