在 JavaScript 中删除重复项并插入空字符串

javascriptweb developmentfront end technologyobject oriented programming更新于 2026/2/3 16:12:17

我们必须编写一个函数,该函数接收一个数组,从中删除所有重复项,并在末尾插入相同数量的空字符串。

例如:

如果我们发现 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,
   '', '', '', '', '', '', '',
   '', '', '', ''
]

相关文章


有用资源