将数组压缩为连续元素分组 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