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

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

Table of Contents

例一:

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

// 方法一
const result = []
duplicate.forEach((num) => {
  if (!result.includes(num)) {
    result.push(num);
  }
})

// 方法二
const result = duplicate.filter((element, index, arr) => {
  return arr.indexOf(element) === index;
});

// 方法三
const result = [...new Set(duplicate)];

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: "新店之眼",
  },
];

// 方法一
const result = [];
scapes.forEach((scape) => {
  if (!result.find(r => r.imageScapeName === scape.imageScapeName)) {
    result.push(scape);
  }
})

// 方法二
const result = scapes.filter((scape, index, arr) => {
  return arr.findIndex(s => scape.imageScapeName === s.imageScapeName) === index;
});

console.log(result);
/* [
  { 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

Your email address will not be published. Required fields are marked *

Scroll to Top