Set
是 ES6 提供的一種新的數(shù)據(jù)結構咒程,類似于數(shù)組,但是成員都是唯一的讼育,不重復的特點帐姻,因此可以通過Set
輕松實現(xiàn)對數(shù)組的 去重、交奶段、并饥瓷、補等操作。
屬性方法如下:
interface Set {
add(value): this;
clear(): void;
delete(value): boolean;
forEach(callbackfn: (value, value2, set: Set) => void, thisArg?: any): void;
has(value): boolean;
readonly size: number;
}
根據(jù)Set
的特點痹籍,有很多場景可以通過Set
快速實現(xiàn)呢铆。
去重
let arr1 = [1, 2, 3, 4, 5, 6, 7, 4, 3, 2, 1];
// 去重
let newArr = [...new Set(arr1)];
console.log(arr1); // [LOG]: [ 1, 2, 3, 4, 5, 6, 7, 4, 3, 2, 1 ]
console.log(newArr); // [LOG]: [ 1, 2, 3, 4, 5, 6, 7 ]
交集、并集蹲缠、補集
let arr1 = [1, 2, 3, 4, 5];
let arr2 = [3, 4, 5, 6, 7];
let arr1_set = new Set(arr1);
let arr2_set = new Set(arr2);
// 交集
let intersectionArr = [...arr1_set].filter(val => arr2_set.has(val));
console.log(intersectionArr ); // [LOG]: [ 3, 4, 5]
// 并集
let unionArr = [...new Set([...arr1, ...arr2])];
console.log(unionArr ); // [LOG]: [ 1, 2, 3, 4, 5, 6, 7 ]
// 補集
let complementaryArr = [...arr1_set].filter(val => !arr2_set.has(val));
console.log(complementaryArr ); // [LOG]: [ 1, 2 ]