Javascriptで配列内の重複を除去する

uniqコマンドみたいな便利な奴がないのでメモ

 

1. filterを使う

var ary = [1, 2, 2, 3, 4, 3];
ary = ary.filter((x, y) => {
    return ary.indexOf(x) === y;
});
//[ 1, 2, 3, 4 ]

 

2. reduceを使う

var ary = [1, 2, 2, 3, 4, 3];
ary = ary.reduce((x, y) => {
    return x.includes(y) ? x : [...x, y];
}, []);
//[ 1, 2, 3, 4 ]

 

3. Setオブジェクトを使う

let ary = [1, 2, 2, 3, 4, 3];
ary = Array.from(new Set(ary));
//[ 1, 2, 3, 4 ]

 
IE?なにそれ?