在 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,
   '', '', '', '', '', '', '',
   '', '', '', ''
]

更新時間: 20-Oct-2020

364 次瀏覽

開啟您的 職業生涯

透過完成課程取得認證

開始
廣告