如何在更改原始数组的同时从数组中找到 & 分组对?
How can I find & groups pairs from an array while changing the original array?
所以对于前。我有这个包含这些值的数组:
let arr = [1, 2, 3, 3, 3, 4, 4];
我怎样才能得到一个新的 arr :
let newArr = [3, 3, 4, 4];
同时应将原始数组更改为:
let arr = [1, 2, 3];
留下一个 3 因为只有一对 3。
我在下面尝试了这段代码(for 循环和拼接),但它无法正常工作。
let result = [];
for (let i = 0; i < sorted.length; i++) {
if (sorted[i] === sorted[i + 1]) {
let pair = sorted.splice(i, 1);
pair.forEach(el => result.push(el));
}
}
几处更正,
- 您需要
splice
从您看到重复项开始的两项。
像这样尝试。
- 迭代停止条件应该是
i < sorted.length - 1
因为我们考虑两个连续的项目。
- 使用 Array.prototype.concat 将重复项加入结果数组。
let sorted = [1, 2, 3, 3, 3, 4, 4];
let result = [];
for (let i = 0; i < sorted.length - 1; i++) {
if (sorted[i] === sorted[i + 1]) {
let pair = sorted.splice(i, 2);
result = result.concat(pair);
i--;
}
}
console.log(sorted)
console.log(result)
所以对于前。我有这个包含这些值的数组:
let arr = [1, 2, 3, 3, 3, 4, 4];
我怎样才能得到一个新的 arr :
let newArr = [3, 3, 4, 4];
同时应将原始数组更改为:
let arr = [1, 2, 3];
留下一个 3 因为只有一对 3。
我在下面尝试了这段代码(for 循环和拼接),但它无法正常工作。
let result = [];
for (let i = 0; i < sorted.length; i++) {
if (sorted[i] === sorted[i + 1]) {
let pair = sorted.splice(i, 1);
pair.forEach(el => result.push(el));
}
}
几处更正,
- 您需要
splice
从您看到重复项开始的两项。 像这样尝试。 - 迭代停止条件应该是
i < sorted.length - 1
因为我们考虑两个连续的项目。 - 使用 Array.prototype.concat 将重复项加入结果数组。
let sorted = [1, 2, 3, 3, 3, 4, 4];
let result = [];
for (let i = 0; i < sorted.length - 1; i++) {
if (sorted[i] === sorted[i + 1]) {
let pair = sorted.splice(i, 2);
result = result.concat(pair);
i--;
}
}
console.log(sorted)
console.log(result)