將陣列壓縮為連續元素分組 JavaScript
我們獲得了包含一些重複單詞的字串,單詞以破折號 (-) 分隔,如下所示 −
const str = 'monday-sunday-tuesday-tuesday-sunday-sunday-monday-mondaymonday';
現在我們的工作是編寫一個函式,該函式返回一個物件陣列,其中每個物件包含兩個屬性:value 和 count,value 是字串中的單詞(星期一、星期二、星期日),而 count 是它們連續出現的次數。
對於如上字串,此陣列將如下所示 −
const arr = [{
val: 'monday',
count: 1
}, {
val: 'sunday',
count: 1
}, {
val: 'tuesday',
count: 2
}, {
val: 'sunday',
count: 2
}, {
val: 'monday',
count: 3
}]因為星期一齣現一次,然後星期日一次,星期二兩次,星期日兩次,最後星期一三次。
我們將拆分陣列,然後使用 Array.prototype.reduce() 方法來遞迴返回所需的陣列,如下所示 −
完整的程式碼如下 −
示例
const str = 'monday-sunday-tuesday-tuesday-sunday-sunday-monday-mondaymonday';
const str2 = 'friday-friday-sunday-tuesday-sunday-sunday-monday-thursdaymonday';
const compressString = (str) => {
return str.split('-').reduce((acc, val) => {
const { length: l } = acc;
if(acc[l-1]?.val === val){
acc[l-1].count++;
return acc;
}else{
return acc.concat({
val,
count: 1
});
}
}, []);
}
console.log(compressString(str));
console.log(compressString(str2));輸出
上述程式碼在控制檯中的輸出將為 −
[
{ val: 'monday', count: 1 },
{ val: 'sunday', count: 1 },
{ val: 'tuesday', count: 2 },
{ val: 'sunday', count: 2 },
{ val: 'monday', count: 3 }
]
[
{ val: 'friday', count: 2 },
{ val: 'sunday', count: 1 },
{ val: 'tuesday', count: 1 },
{ val: 'sunday', count: 2 },
{ val: 'monday', count: 1 },
{ val: 'thursday', count: 1 },
{ val: 'monday', count: 1 }
]
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP