Two ways for JavaScript to judge duplicate content in an array by Fungleo preface
In general, we may give the array the weight, the operation is not complex, the execution of a loop is. Now, what I'm going to do is to determine if there are duplicate contents in the array, and if so, return true
otherwise false
.
Ideas
- To turn an array into a string
- Loop the original array, take each field and the string to compare, see if there are duplicates
How do A字符串
you B字符串
compare and contrast, and ask to B字符串
know if it contains one A字符串
?
Method one indexOf () and lastIndexOf () contrast method.
First, we build the code:
var arr = ["aa","bb","cc","bb","aa"];arrRepeat(arr);
As above, we are going to use a arrRepeat(arr)
check function and execute it, and build the function below.
function arrRepeat(arr){ varJSON.stringify(arr),str; for (var0; i < arr.length; i++) { if (arrStr.indexOf(arr[i]) != arrStr.lastIndexOf(arr[i])){ returntrue; } }; returnfalse;}
OK, run successfully.
The principle is particularly simple, that is, the field in the array, the first occurrence and the last occurrence position in the string changed by the array, if not consistent, it shows that this repetition occurs.
Method two match () regular comparison method
First, as with the above, we build the code:
var arr = ["aa","bb","cc","bb","aa"];arrRepeat(arr);
Then we re-construct the arrRepeat(arr)
function
f Unction arrrepeat (arr) { var arrstr = json . Stringify (arr), str; for (var i = 0 ; i < arr.length; i++) {if (Arrstr.match (new regexp (Arr[i],)). Length) >1 ) {return true ; } }; return false ;}
The principle is to find a certain number of repetitions, if it is greater than 1, it must be repeated. Note that here is able to accurately find out how many times it appeared! So, this method actually has a wider use.
OK, run another success
Summarize
- If only the first method is actually enough.
- The second method can find the actual number of occurrences, such as repeated 4 times, you can find 4. Specific uses to think about it.
- The way to build a regular with variables
new RegExp(arr[i],"g")
is to ask someone to ask them.
- In fact, I first thought of is the second idea, the problem of the regular half-day, finally solved. Just think of the first idea.
This article is original by Fungleo, allow reprint. But reprint must be signed by the author, and keep the article starting link. Otherwise, legal liability will be investigated.
Starting Address: http://blog.csdn.net/FungLeo/article/details/51596404
Two ways for JavaScript to judge duplicate content in an array by Fungleo