[JavaScript] ES6 Array 移除重複(Distinct)

Banner

以下提供兩種排除陣列重複值的方式。

使用 filter 方法

1
2
3
4
5
6
7
const array1 = ['a', 'b', 'c', 'g'];
const array2 = ['d', 'a', 'b'];

const newArray = [...array1, ...array2];
const result = newArray.filter((value, index, self) => self.indexOf(value) === index);
console.log(result);
// output: Array ["a", "b", "c", "g", "d"]

此方法是使用 JavaScript 的 filter() 方法來進行過濾,藉由判斷 indexOf() 方法所查詢出 value 的索引值(index)是否與當前相同,以此來排除重複值。

使用 Set 物件

除了 filter 方法也可使用 JavaScript 的 Set 物件,因為 Set 物件只會幫你儲存任何類型的唯一值(unique),程式碼如下。

1
2
3
4
5
6
const array1 = ['a', 'b', 'c', 'g'];
const array2 = ['d', 'a', 'b'];

const result = Array.from(new Set([...array1, ...array2]));
console.log(result);
// output: Array ["a", "b", "c", "g", "d"]