Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

JavaScript Remove duplicates from text/array

I want to remove lines in text based on duplicate keywords. The text goes something like this.

text1,abc,text2
text3,cde,text4
text5,abc,text6
text7,gfh,text8
text9,cde,text10

I want to make it into.

text1,abc,text2
text3,cde,text4
text7,gfh,text8

The idea is to take the text, split it based on lines and put it through 2 loops. Then comparing the two arrays it would remove duplicates from it. How can I do this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Here's a jsFiddle that will remove duplicates in the middle column of your data array: http://jsfiddle.net/bonneville/xv90ypgf/

var sortedAr = ar.sort(sortOnMiddleText);
var noDupsAr = removeDups(sortedAr);

Firstly is sorts on the middle column, and then it removes the duplicates. The code is pure javascript but uses jQuery to display the results. (I would prefer to use javaScript forEach instead of the for loop but it is not supported on all browsers so you would need a polyfill.)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...