如果我有一个数字数组,例如:[1,2,3,3,3,4,4,8]
,并且我删除了元素2,那么我的目标是保持数组的顺序,但是将值移动一个保留重复项。所以我要找的结果是:[1,2,2,2,3,3,4]
。我将所有重复项都视为一组数字。
帮助将不胜感激!
答案 0 :(得分:0)
使用Array#reduce
过滤掉要删除的号码,然后移动群组:
function regroup(arr, numToRemove) {
var last;
var current;
return arr.reduce(function(r, num) {
if(current !== undefined && num !== current) {
last = current;
current = num;
}
if(last !== undefined) {
r.push(last);
} else if(num === numToRemove) {
current = num;
} else {
r.push(num);
}
return r;
}, []);
}
var arr = [1,2,3,3,3,4,4,8, 25, 25, 25, 30, 30, 31];
var result = regroup(arr, 2);
console.log('origin: ', JSON.stringify(arr));
console.log('result: ', JSON.stringify(result));

答案 1 :(得分:0)
假设原始问题有分组值并获得此结果,通过为组设置最后一个值,则此提议适用于此。
1 2 3 3 3 4 4 8 1 2 2 2 3 3 4 ^ remove
var array = [1, 2, 3, 3, 3, 4, 4, 8],
number = 2,
result = array.reduce(function () {
var last, next;
return function (r, a) {
if (last === undefined) {
if (a === number) {
last = a;
} else {
r.push(a);
}
} else {
if (a === number) {
return r;
}
if (next === undefined) {
next = a;
}
if (a !== next) {
last = next;
next = a;
}
r.push(last);
}
return r;
};
}(), []);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }