Preface
Generally, we may deduplicate the array. This operation is not complicated, just execute a loop. Now, what I want to do is to determine whether there is duplicate content in the array. If so, return true. Otherwise, return false.
Ideas
Turn an array into a string
Loop the original array, compare each field with this string to see if there is any duplication
How to compare A string with B string and B string and ask to determine that B string contains A string?
Methods: indexOf() and lastIndexOf() comparison method.
First, we build the code:
var arr = ["aa","bb","cc","bb","aa"];arrRepeat(arr);
As mentioned above, we need to use arrRepeat(arr) verification function and execute it. Let's build this function below
function arrRepeat(arr){var arrStr = JSON.stringify(arr),str;for (var i = 0; i < arr.length; i++) {if (arrStr.indexOf(arr[i]) != arrStr.lastIndexOf(arr[i])){return true;}};return false;}OK, the run was successful.
The principle is particularly simple, that is, whether the first occurrence position and last occurrence position of the fields in the array are consistent in the string transformed from an array. If it is inconsistent, it means that this recursive appears.
Method 2 match() Regular comparison method
First, as above, we build the code:
var arr = ["aa","bb","cc","bb","aa"];arrRepeat(arr);
Then, we rebuild the arrRepeat(arr) function
function arrRepeat(arr){var arrStr = JSON.stringify(arr),str;for (var i = 0; i < arr.length; i++) {if ((arrStr.match(new RegExp(arr[i],"g")).length)>1){return true;}};return false;}The principle is to find the number of repetitions that are determined. If it is greater than 1, it will definitely be repeated. Note that this can accurately find out how many times it has appeared! Therefore, this method actually has a wider purpose.
OK, the run succeeded again
Summarize
If you just compare the first method, it is actually enough.
The second method can find the real number of times that appear. For example, if you repeat 4 times, you can find 4. Think about the specific purpose by yourself.
The method to build a regular method containing variables new RegExp(arr[i],"g") is also asked by others.
Actually, what I thought of first was the second idea. The regular problem was troubled by a long time and finally solved it. Only then did I think of the first idea.
The above are two methods (recommended) for judging duplicate content in JavaScript introduced to you by the editor (recommended). I hope it can help you!