https://zhidao.baidu.com/question/499457440.html
这位老哥id dllgdx_2000
代码1 去重复数据
<script>
Array.prototype.distinct = function() {
var a = [],
b = [];
for (var prop in this) {
var d = this[prop];
if (d === a[prop]) continue; //防止循环到prototype
if (b[d] != 1) {
a.push(d);
b[d] = 1;
}
}
return a;
}
var x = ['a', 'b', 'c', 'd', 'b', 'a', 'e', 'a', 'b', 'c', 'd', 'b', 'a', 'e'];
document.write('原始数组:' + x);
document.write("<br />");
document.write('去重复后:' + x.distinct());
</script>
输出结果
原始数组:a,b,c,d,b,a,e,a,b,c,d,b,a,e
去重复后:a,b,c,d,e
代码2 取重复数据
<script type="text/javascript">
Array.prototype.distinct = function() {
var a = [],
b = [],
c = [],
d = [];
for (var prop in this) {
var d = this[prop];
if (d === a[prop]) {
continue;
} //防止循环到prototype
if (b[d] != 1) {
a.push(d);
b[d] = 1;
} else {
c.push(d);
d[d] = 1;
}
}
//return a;
return c.distinct1();
}
Array.prototype.distinct1 = function() {
var a = [],
b = [];
for (var prop in this) {
var d = this[prop];
if (d === a[prop]) continue; //防止循环到prototype
if (b[d] != 1) {
a.push(d);
b[d] = 1;
}
}
return a;
}
var x = ['a', 'b', 'c', 'd', 'b', 'a', 'e', 'a', 'b', 'c', 'd', 'b', 'a', 'e'];
document.write('原始数组:' + x);
document.write("<br />");
document.write('取重复后:' + x.distinct());
</script>
结果输出
原始数组:a,b,c,d,b,a,e,a,b,c,d,b,a,e
取重复后:b,a,c,d,e