日期:2014-05-16  浏览次数:20293 次

js实现数据去重复
今天刚出炉的,百度空间里也有

今天应朋友的需要写了个简单的txt文件内容去重复的js代码。

这段代码可以处理txt文件中的重复数据,但是前提是该txt文件每行是一条数据记录。

使用时,将该代码文件保存为任意名称的.html文件与你的txt源文件放到一个目录中,

运行该html文件,输入源txt文件的名称(注意不要带后缀.txt)点“去重”弹出框选择是

就会显示程序运行信息,并在该文件目录下生成一个test.txt文件。

例如:

目录结构:

D:/test/src.txt源文件

D:/test/test.html程序文件

D:/test/test.txt被生成文件

代码:

源文件:src.txt

13252491322132463
1323474226755

1323484945088
132340913294263
132377234213223
1323572633507
132592922813222
1323772329827
1325289426908
132529132280304
1323720690326
132871327636838
1323484945088
132522944132363
13238913228765

处理文件 test.html

<html>
<body>

<IE:Download ID="oDownload1" STYLE="behavior:url(#default#download)" />
<script>
var my_array = new Array();
function onDownloadDone(downData){
document.getElementById('showImport1').innerHTML=downData;
}

function txt2array(downData){
    my_array = downData.split("/r/n");
    //document.write('去重复后:'+downData);
    //CreateFile();
    }
function CreateFile(tt)
{
   var fso, tf;
   fso = new ActiveXObject("Scripting.FileSystemObject");
   tf = fso.CreateTextFile("test.txt", true);
   tf.WriteLine(tt) ;
   tf.Close();
}
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;
}
function dosub(){
    var filname= document.getElementById('txtid').value;
    oDownload1.startDownload(filname+'.txt',txt2array);
        var test1 =my_array.distinct();
        var getstr =test1.toString();
        re = /,/g;
        var strtrans =getstr.replace(re,"/r/n");
        CreateFile(strtrans);
        document.getElementById('show_info').innerHTML="去重复成功:<br/>源文件行数:"+my_array.length+'去除后行数为:'+test1.length;
    }

//document.write("去重复成功:<br/>源文件行数:"+my_array.length+'去除后行数为:'+test1.length);

//document.write('去重复后:'+my_array.distinct()+"<hr/>"+my_array.distinct().length);
</script>
<table width="500" border="0" align="center" cellpadding="0" cellspacing="0">
        <tr onmouseover="this.style.background='#FFFFFF'" onmouseout="this.style.background=''">
          <td width="120" align="center"><strong>说明</strong></td>
           <td align="left"><strong>txt文件去重复</strong></td>
</tr>
        <tr onmouseover="this.style.background='#FFFFFF'" onmouseout="this.style.background=''">
          <td align="center">源文件名</td>
          <td align="left"><label&g