在JavaScript中插入空字符串代替重复值
我们必须编写一个函数,该函数接受数组,从数组中删除所有重复项,并在末尾插入相同数量的空字符串。
例如:如果发现4个重复值,则必须删除所有值,然后在末尾插入四个空字符串。
因此,让我们为该函数编写代码-
示例
为此的代码将是-
const arr = [1,2,3,1,2,3,2,2,3,4,5,5,12,1,23,4,1];
const deleteAndInsert = arr => {
const creds = arr.reduce((acc, val, ind, array) => {
let { count, res } = acc;
if(array.lastIndexOf(val) === ind){
res.push(val);
}else{
count++;
};
return {res, count};
}, {
count: 0,
res: []
});
const { res, count } = creds;
return res.concat(" ".repeat(count).split(" "));
};
console.log(deleteAndInsert(arr));输出结果
控制台中的输出将为-
[ 2, 3, 5, 12, 23, 4, 1, '', '', '', '', '', '', '', '', '', '', '' ]
热门推荐
1 狗狗下楼训练
3 狗狗训练头盔
6 狗狗训练机构
7 训练狗狗步骤
9 狗狗能训练
10 狗狗基本动作训练方法
11 怎么训练狗狗叼饭盆
12 狗狗一岁了还能训练吗
13 训练狗狗的
14 宁波狗狗训练
15 训练狗狗拉屎
16 教狗狗训练
17 狗狗要怎么训练上厕所
18 狗狗靠的训练