刪除重複項並在 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,
   '', '', '', '', '', '', '',
   '', '', '', ''
]

更新時間:2020-10-20

249 次瀏覽

開啟你的職業生涯

完成課程即可獲得認證

開始
廣告
© . All rights reserved.