从数组中删除重复项,使其在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, '', '', '', '', '', '', '', '', '', '', '' ]
热门推荐
10 红包祝福语简短10字
11 高考录取庆贺祝福语简短
12 新年祝福语大全牛年 简短
13 妈妈生日祝福语简短优美
14 南宁招生老师祝福语简短
15 年末祝福语简短小清新
16 小朋友上学祝福语简短
17 妹妹生日祝福语简短好看
18 对当兵的祝福语简短