所以對于前。我有這些值的陣列:
let arr = [1, 2, 3, 3, 3, 4, 4];
我怎樣才能得到一個新的 arr:
let newArr = [3, 3, 4, 4];
同時原始陣列應更改為:
let arr = [1, 2, 3];
留下一個 3,因為只有一對 3。
我在下面嘗試了這段代碼(a for loop & splice),但它不能正常作業。
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));
}
}
uj5u.com熱心網友回復:
糾正了幾件事,
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)
}
}
console.log(sorted)
console.log(result)
uj5u.com熱心網友回復:
感謝塞巴斯蒂安西蒙,它現在可以作業了。
for (let i = 0; i < sorted.length; i ) {
if (sorted[i] === sorted[i 1]) {
let pair = sorted.splice(i, 2);
pair.forEach(el => result.push(el));
i--;
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/409522.html
標籤:
