js中怎么把数组中重复的数据取出来

如题所述

需要准备的材料分别是:电脑、html编辑器、浏览器。

1、首先,打开html编辑器,新建html文件,例如:index.html。

2、在index.html的<script>标签中,输入js代码:

var a = [1, 6, 8, 5, 23, 6, 6, 7, 8], b = [], c = [];

for (var i = 0; i < a.length; i++) {

if (c.indexOf(a[i]) === -1) {

c.push(a[i]);

} else {

b.push(a[i]);

}

}

document.body.innerText = b;

3、浏览器运行index.html页面,此时会打印出数组a中重复的数据。

温馨提示:答案为网友推荐,仅供参考
第1个回答  2016-06-08
js数组中取重复数据的方法:
方法一:去重复数据
<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>
方法二:取重复数据
<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','f','f','g'];
document.write('原始数组:'+x);
document.write("<br />");
document.write('去重复后:'+x.distinct());
</script>本回答被提问者和网友采纳
第2个回答  2016-06-27

  思路:定义一个空的新数组,然后循环目标数组,判断,新数组中是否包含循环的数据,如果不包含就放入新的数组。

  代码示例:

var myArr = [1,2,3,3,4,5,6,6];
var newArr = [];
for(var s in myArr){
    if(newArr.indexOf(myArr[s])<0){
        newArr.push(myArr[s]);
    }
}

最终。newArr就是去重后的数据

第3个回答  2016-07-08
把数组元素逐个搬运到另一个数组,搬运的过程中检查这个元素是否有重复,如果有就直接丢掉
function unique(arr) {
var result = [], isRepeated;
for (var i = 0, len1 = arr.length; i < len1; i++) {
isRepeated = false;
for (var j = 0, len = result.length; j < len; j++) {
if (arr[i] == result[j]) {
isRepeated = true;
break;
}
}
if (!isRepeated) {
result.push(arr[i]);
}
}
return result;
}
或者:
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;
}
var arr1=[5,6,3,7,6];
alert(unique(arr1));
第4个回答  2016-06-17
第一种:

function unique(arr) {
var result = [], isRepeated;
for (var i = 0, len = arr.length; i < len; i++) {
isRepeated = false;
for (var j = 0, len = result.length; j < len; j++) {
if (arr[i] == result[j]) {
isRepeated = true;
break;
}
}
if (!isRepeated) {
result.push(arr[i]);
}
}
return result;
}
第二种:

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;

}
相似回答