js-array, remove the duplicate

Source: Internet
Author: User

For a fixed known array such as:var arr = [' name ', ' OK ', ' 123 ', ' n ', ' look ', ' 777 ', ' n ', ' 123 ', ' name ', 1,3,5,1, ' OK '];

So the question is, how can we get rid of the duplicate strings or numbers, getting a new array?

Method ①:

function takerepetition_1 (arr) {
var data= {}; //This will traverse the data's arr[i] property because the data is empty for the return undefined
var result = [];
For (Var i=0;i<arr.length;i++) {
if (!json[arr[i]]) {
Json[arr[i]] = 1; //So when if satisfied! Undefined is true when the value of the Arr[i] property of data is set to 1
Result.push (Arr[i]); ///And then put in the result array so if there are duplicate values in the ARR array, the If does not meet the criteria will not be added to the array
}
}
return result;
}
Console.log (Unqiue (arr));


method ②:
Array.prototype.takeRepetition_2 = function () { //two cycles iterating through an array, comparing values
var a = [];
var L = this.length;
For (var i = 0;i< l; i++){ 
For (var j = i + 1; j < L; j + +) {
if (this[i] = = = This[j]) {

j = ++i

}
}
A.push (This[i]);
}
return A;
}
Console.log (Arr.takerepetition_2 ());

Method ③:

array.prototype.takerepetition _3 = function () {

var n = []; //A new temporary array
for (var i = 0; i < this.length; i++) { //If the current array is already saved in the temporary array, skip, otherwise push the current item into the temporary array
if (N.indexof (this[i]) = =-1) n.push (This[i]);
}
return n;
}
Console.log (Arr.takerepetition_3 ());

All right, welcome to a different way to discuss it together! ~~~~~

js-array, remove the duplicate

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.