ES6 提供了新的数据结构 Set。它类似于数组,但是成员的值都是唯一的,没有重复的值。
数组去重的方法1:
const arr = [2, 3, 5, 4, 5, 2, 2];
const s = new Set();
arr.forEach(x => s.add(x));
for (let i of s) {
console.log(i);
}
// 2 3 5 4
上面代码通过add()方法向 Set 结构加入成员,结果表明 Set 结构不会添加重复的值。
数组去重的方法2:
[...new Set([1,2,2,3,3,4,4,4,4])]
// [1, 2, 3, 4]
数组去重的方法3:
let result = Array.from(new Set([1,1,2,2,2,3,3,3,4]));
console.log(result); // [1, 2, 3, 4]
字符串去重:
[...new Set('ababbc')].join('')
// [...new Set('ababbc')]得到的是不重复的数组['a','b','c']
// .join('')将数组['a','b','c']转为字符串'abc'