【JavaScript】如何刪除陣列重複項

最近實作後端時需要刪除陣列重複項,但google了一下發現方法都好複雜,所以後來乾脆自己想,紀錄一下自己的方法~

例一:

const duplicate = [1, 1, 2, 3, 4, 4, 5, 5, 5]

const result = []
// 宣告一個新的陣列

duplicate.forEach((e, i) => {
  if (i === 1) {
    result.push(e)
  // 先把第一個元素放到新陣列中
  } else {
  // 對舊陣列的每個元素執行以下函數
    for (const value of result) {
      if (result.find(el => el === e)) {
      // 如果在新陣列中有找到當前就陣列的元素,就return
        return
      } else {
      // 否則就將當前元素puah到新陣列中
        result.push(e)
      }
    }
  }
})

console.log(result)
// [ 1, 2, 3, 4, 5 ]

例二:

const scapes = [
  {
    image: "uploads/images1",
    imageScapeName: "九份",
  },
  {
    image: "uploads/images2",
    imageScapeName: "新店之眼",
  },
  {
    image: "uploads/images3",
    imageScapeName: "九份",
  },
  {
    image: "uploads/images4",
    imageScapeName: "九份",
  },
  {
    image: "uploads/images5",
    imageScapeName: "新店之眼",
  },
  {
    image: "uploads/images6",
    imageScapeName: "新店之眼",
  },
];

scapeInCity = [];
scapes.forEach((image, index) => {
  if (index == 0) {
    scapeInCity.push(image);
  } else {
    for (const value of scapeInCity) {
      if (
        scapeInCity.find(
          (element) => element.imageScapeName === image.imageScapeName
        )
      ) {
        break;
      } else {
        scapeInCity.push(image);
      }
    }
  }
});
console.log(scapeInCity);
/* [
  { image: 'uploads/images1', imageScapeName: '九份' },
  { image: 'uploads/images2', imageScapeName: '新店之眼' }
] */

例三:

let arr = [1, 2, 1, 2, 3, 5, 4, 5];
let result = arr.sort().reduce((init, current) => {
    if (init.length === 0 || init[init.length - 1] !== current) {
        init.push(current);
    }
    return init;
}, []);
console.log(result); //[1,2,3,4,5]

Leave a Comment

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *

Scroll to Top