title: 数组去重的几个方法
date: 2017-11-11
tags: mac apache CGI
数据去重
//1、排序去重
var arr = [1, 4, 5, 6, 20, 3, 5, 7, 2, 3, 2, 1, 6, '1'];
arr.sort(function(a, b) {
return a - b;
});
console.log(arr);
var result = [];
var len = arr.length;
for (var i = 0; i < len; i++) {
if (arr[i] !== arr[i + 1]) {
result.push(arr[i]);
}
}
console.log(result);
//2、不排序直接去重
var arr2 = [1, 4, 5, 6, 20, 3, 5, 7, 2, 3, 2, 1, 6, '1'];
function unique2(arr2) {
var len2 = arr2.length;
var result2 = [],
falg;
for (var i = 0; i < arr2.length; i++) {
flag = false;
for (var j = i + 1; j < arr2.length; j++) {
if (arr2[i] === arr2[j]) {
//有相等
flag = true;
break;
}
}
if (!flag) {
result2.push(arr2[i]);
}
}
return result2;
}
//3 第三种方式 利用hashTable
function unique(arr) {
var result = [],
hash = {};
for (var i = 0, elem;
(elem = arr[i]) != null; i++) {
if (!hash[elem]) {
result.push(elem);
hash[elem] = true;
}
}
return result;
}
console.log("11");
console.log(unique(arr2));
var num1 = 100;
console.log(~num1); //-101
var num = 0;
for (var i = 0; i < 10; i++) {
for (var j = 0; j < 10; j++) {
if (i == 5 && j == 5) {
break;
}
num++;
}
}
//alert(num);
function add(num1, num2) {
arguments[1] = 10;
return arguments[0] + arguments[1];
}
var a = 5,
b = 20;
console.log(add(a, b));
console.log(b);
个人感觉hash去重的效果较好
网友评论