在 JavaScript 中移除数组中的重复项,且保持其长度不变
我们必须编写一个函数,该函数以一个数组为输入,从中移除所有重复项并插入相同数量的空字符串到结尾处。
例如,如果我们发现 4 个重复值,我们必须移除所有这些值,并在结尾处插入 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, '', '', '', '', '', '', '', '', '', '', '' ]
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP