媒介
總結了一下有關於數組的差集、交集、並集的要領;
es6的要領完成
去重
/**
* 簡樸的數組去重
* @param {Array} a
*/
const uniquelize = function(a) {
if (a.constructor !== Array) {
throw TypeError("請傳入數組範例");
}
return Array.from(new Set(a));
};
並集
/**
* 簡樸數組的並集
* @param {Array} a
* @param {Array} b
*/
const getUnion = function(a,b){
if(a.constructor === Array && b.constructor === Array){
let set1 = new Set(a);
let set2 = new Set(b);
return Array.from(new Set([...set1,...set2]));
}
return null;
}
交集
/**
* 簡樸數組的交集
* @param {Array} a
* @param {Array} b
*/
const getIntersect = function(a,b){
if(a.constructor === Array && b.constructor === Array){
let set1 = new Set(a);
let set2 = new Set(b);
return Array.from(new Set([...set1].filter( x => set2.has(x))));
}
return null;
}
差集
/**
* 簡樸數組的差集
* @param {Array} a
* @param {Array} b
*/
const getDifference = function(a,b){
if(a.constructor === Array && b.constructor === Array){
let set1 = new Set(a);
let set2 = new Set(b);
return Array.from(new Set([...set1].filter(x => !set2.has(x))));
}
return null;
}
es5的要領完成
去重
/**
* 簡樸的數組去重
* @param {Array} a
*/
var uniquelize = function(a) {
if (a.constructor !== Array) {
throw TypeError("請傳入數組範例");
}
var obj = {},
arr = [];
for (var i = 0, j = a.length; i < j; i++) {
if (!obj[a[i]]) {
obj[a[i]] = 1;
arr.push(a[i]);
}
}
return arr;
};
交集
/**
* 簡樸數組的交集
*/
var getIntersect = function(){
var arr = new Array();
var obj = new Object();
var arguLen = arguments.length;
for(var i = 0; i<arguLen;i++){
if(arguments[i].constructor !== Array){
throw TypeError("請都傳入數組範例");
}
for(var j = 0,length = arguments[i].length;j<length;j++){
var item = arguments[i][j];
if(!obj[item]){
obj[item] = 1;
}else{
obj[item]++;
if(obj[item]===arguLen){
arr.push(item);
}
}
}
}
return arr;
}
並集
/**
* 簡樸數組的並集
*/
var getUnion = function(){
var arr = new Array();
var obj = new Object();
var arguLen = arguments.length;
for(var i = 0; i<arguLen;i++){
if(arguments[i].constructor !== Array){
throw TypeError("請都傳入數組範例");
}
for(var j = 0,length = arguments[i].length;j<length;j++){
var item = arguments[i][j];
if(!obj[item]){
obj[item] = 1;
arr.push(item);
}else{
//統計一下湧現了多少次
obj[item]++;
}
}
}
return arr;
}
差集
/**
* 簡樸數組的差集
*/
var getDifference = function(){
var arr = new Array();
var obj = new Object();
var arguLen = arguments.length;
for(var i = 0; i<arguLen;i++){
if(arguments[i].constructor !== Array){
throw TypeError("請都傳入數組範例");
}
for(var j = 0,length = arguments[i].length;j<length;j++){
var item = arguments[i][j];
if(!obj[item]){
obj[item] = 1;
arr.push(item);
}else{
obj[item]++;
var index = arr.indexOf(item);
//存在就刪撤除
if(index !== -1){
arr.splice(index,1);
}
}
}
}
return arr;
}