[js] 数组去重、交集、并集
去重
function array_unique(arr) { var result = [arr[0]], isRepeat; for (var i = 0; i < arr.length; i++) { isRepeat = false; for (var j = 0; j < result.length; j++) { if (result[j] === arr[i]) { isRepeat = true; break; } } if (!isRepeat) { result.push(arr[i]); } } return result; }
取重
function array_repeat(arr) { var result = [], length = arr.length; for (var i = 0; i < length; i++) { for (j = i + 1; j < length; j++) { if (arr[i] === arr[j]) { result.push(arr[i]); } } } return array_unique(result); } console.warn(array_repeat([4, 3, 2, 1, 6, 6, 1, 2, 3, 4, 5])); console.warn(array_repeat([4, 3, 2, 1, 5, 2, '5', 1, 2, 3, 4, 5, 3]));
取差,删除重复元素
function array_difference(arr) { var result = [], length = arr.length, l; for (var i = 0; i < length; i++) { for (j = 0; j < length; j++) { if (arr[i] === arr[j]) { result.push(j); } } } l = array_unique(result).length; for (var i = 0; i < l; i++) { var k = result[i]; delete arr[k]; } return arr; }; console.warn(array_difference([4, 3, 2, 1, 6, 6, 1, 2, 3, 4, 5])); console.warn(array_difference([4, 3, 2, 1, 5, 2, '5', 1, 2, 3, 4, 5, 3]));
并集
function array_union(arr1, arr2) { var a1 = array_unique(arr1), a2 = array_unique(arr2), c = a1.concat(a2); return array_unique(c); }; console.log(array_union([4, 3, 2, 1, 6, 6], [1, 2, 3, 4, 5])); console.log(array_union([4, 3, 2, 1, 5, 2], ['5', 1, 2, 3, 4, 5, 3]));
交集
function array_intersection(arr1, arr2) { var a1 = array_unique(arr1), a2 = array_unique(arr2), c = a1.concat(a2); return array_repeat(c); }; console.log(array_intersection([4, 3, 2, 1, 6, 6], [1, 2, 3, 4, 5])); console.log(array_intersection([4, 3, 2, 1, 5, 2], ['5', 1, 2, 3, 4, 5, 3]));
差集
function array_diff(a, b) { var temp = [], status; for (var i = 0; i < a.length; ++i) { status = true; for (var j = 0; j < b.length; ++j) { if (a[i] === b[j]) { status = false; break; } } if (status) { temp.push(a[i]); } } return temp; }
Array.prototype.indexOf 兼容方法
if (!Array.prototype.indexOf) { Array.prototype.indexOf = function(searchElement, fromIndex) { var k; if (this == null) { throw new TypeError('"this" is null or not defined'); } var O = Object(this); var len = O.length >>> 0; if (len === 0) { return -1; } var n = +fromIndex || 0; if (Math.abs(n) === Infinity) { n = 0; } if (n >= len) { return -1; } k = Math.max(n >= 0 ? n : len - Math.abs(n), 0); while (k < len) { if (k in O && O[k] === searchElement) { return k; } k++; } return -1; }; }
# ES5去重
function array_diff(a, b) { return a.filter(function(x) { return b.indexOf(x) == -1; }); }