Jimmy 的架站筆記

嗨~我是 Jimmy!我可能不是你認識的第 1 個 Jimmy,但一定是最帥的那個。


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

By Jimmy 2020-11-27
發表於 javascript front-end-note
【JavaScript】如何刪除陣列重複項

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

例一:

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]

你可能也會喜歡

【JavaScript基礎】:Array Methods — 陣列方法整理

【JavaScript基礎】:Array Methods — 陣列方法整理

陣列(array)屬於物件(object)的一種,在Javacript中有許多陣列方法(array methods)可做轉換或運算,來整理一下在看到陣列常見和相關的方法。 1. Array and String:陣列與字串的轉換 字串與陣列相關的方法 1.1 字串轉換成陣列 1.1.1 **Array.from()** 這個方法不只可以轉換字串,還可以轉換類陣列等等。 語法: > Array.f

Read More