将数组简化为JavaScript中的组
假设我们有一个字符串数组,其中包含一些重复的条目,例如:
const arr = ['blue', 'blue', 'green', 'blue', 'yellow', 'yellow', 'green'];
我们需要编写一个包含一个这样的数组的JavaScript函数。该功能应将所有重复的条目相互合并。
因此,上述输入的输出应如下所示:
const output = ['blueblue', 'green', 'blue', 'yellowyellow', 'green'];
示例
为此的代码将是-
const arr = ['blue', 'blue', 'green', 'blue', 'yellow', 'yellow',
'green'];
const combineDuplicate = (arr = []) => {
let prev = null;
const groups = arr.reduce((acc, value) => {
if (prev === value) {
acc[acc.length - 1] += value;
} else {
prev = value
acc.push(value)
}
return acc;
}, [])
return groups;
};
console.log(combineDuplicate(arr));输出结果
控制台中的输出将是-
[ 'blueblue', 'green', 'blue', 'yellowyellow', 'green' ]
热门推荐
10 新年门口花束祝福语简短
11 盘锦结婚祝福语大全简短
12 父母生日祝福语 简短独特
13 家庭恩爱祝福语简短英文
14 高考俄语祝福语大全简短
15 虎年祝福语 诗句唯美简短
16 生日婚礼祝福语简短精辟
17 虎年喝酒拜年祝福语简短
18 教师闺蜜祝福语简短