The first time you see this topic, the idea is to find the duplicate elements in the array, and then delete them. The following is a specific code implementation:
var data = [' Blue ', ' red ', ' green ', ' Blue ']; function Uniquedata (data) { = data.sort (); for (var i = 0; i < data.length; i++) { if (data[i] = = = Data[i + 1] ) {1< c14>); } } return data;} Uniquedata (data);
The above method is relatively simple, but the disadvantage is that after using the sort () method, the original array is changed, the following is the optimized code:
var data = [' Blue ', ' red ', ' green ', ' Blue ']; function Uniquedata (data) { for (var i = 0; i < data.length; i++) { for (J = i + 1; J < Data.length; J+ + ) {if (data[i] = = = Data[j]) { 1); }}} return data;} Uniquedata (data);
Above this method, iterate over the elements in the array, compare any of the two are equal, if you want to wait, the next one from the array to remove, but if the array of elements, this method does not seem so good.
Here is another way of thinking about creating a new array, adding elements from the original array to the new array (judging whether the new array already contains elements from the original array, and if not, adding the elements from the original array to the new array, if they already exist, without adding them), so you can avoid repeating the elements. Take a look at the following code:
var data = [' Blue ', ' red ', ' green ', ' Blue ']; function NewData (data) { varnew Array (); for (var i = 0; i < data.length; i++) { if (Ndata.indexof (data[i]) = =-1) {
ndata.push (Data[i]); } }
return Ndata;} NewData (data);
How do I eliminate repeating elements in an array? (Interview topics)