開心生活站

位置:首頁 > IT科技 > 

es6數組去重

IT科技1.49W

es6數組去重的方法其實是有三種的,即利用Set對象和數組的from方法,具體的代碼語法爲“array.from(new Set(arr))”;利用Set與擴展運算符的方法,具體的代碼語法爲“[...new Set(arr)]”;利用Map對象與數組的filter方法。

es6數組去重

參考範例:

1、利用Set對象和數組的from方法,具體的代碼語法爲“Array.from(new Set(arr))”。

示例代碼:

const newArr = Array.from(new Set(arr));

代碼使用範例:

var arr = [1,1,8,8,12,12,15,15,16,16];

function unique (arr) {

  return Array.from(new Set(arr))

}

console.log(unique(arr))

 //[1,8,12,15,16]

2、利用Set與擴展運算符,具體的代碼語法爲“[...new Set(arr)]”。

示例代碼:

const newArr = [...new Set(arr)];

es6數組去重 第2張

3、利用Map對象與數組的filter方法。

代碼使用範例:

function unique(arr) {

    const res = new Map();

    return arr.filter((a) => !res.has(a) && res.set(a, 1))

}

標籤:數組 es6