压缩数组以对连续元素进行分组 JavaScript
javascriptweb developmentobject oriented programming更新于 2025/9/29 21:00:17
我们得到一个字符串,其中包含一些用破折号 (-) 分隔的重复单词,如下所示 −
const str = 'monday-sunday-tuesday-tuesday-sunday-sunday-monday-mondaymonday';
现在我们的工作是编写一个返回对象数组的函数,其中每个对象包含两个属性 value 和 count,value 是字符串中的单词(Monday、Tuesday、Sunday),count 是它们连续出现的次数。
与上面的字符串一样,这个数组看起来像这样 −
const arr = [{
val: 'monday',
count: 1
}, {
val: 'sunday',
count: 1
}, {
val: 'tuesday',
count: 2
}, {
val: 'sunday',
count: 2
}, {
val: 'monday',
count: 3
}]
因为 monday 出现一次,然后 sunday 出现一次, tuesday 出现两次,sunday 出现两次,monday 出现三次。
我们将拆分数组,然后使用 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 }
]
相关文章
有用资源
javascript 参考教程 - 该教程包含有关 javascript 的更多信息:https://www.cainiaomax.com/javascript/

