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

更新日期: 26-8-2020

149 次瀏覽

開啟你的 職業生涯

完成課程並獲得認證

開始
廣告
© . All rights reserved.