从数组中删除相同的条目,并保持其长度相同-JavaScript
我们必须编写一个函数,该函数接受数组,从数组中删除所有重复项,并在末尾插入相同数量的空字符串。
例如-
如果找到四个重复值,则必须全部删除,然后在末尾插入四个空字符串。
示例
以下是代码-
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, '', '', '', '', '', '', '', '', '', '', '' ]
热门推荐
10 病人祝福语老师寄语简短
11 新娘生孩子祝福语简短
12 婆婆66岁祝福语简短
13 今天孩子高考祝福语简短
14 送彩票生日祝福语简短
15 分别祝福语简短情话英文
16 画室揭牌仪式祝福语简短
17 女友妈妈生日祝福语简短
18 离别赠言离职祝福语简短