Multiple methods of array de-weight implementation

Source: Internet
Author: User

<script>

The first way
var arr=[23,1,34,7,1,3,5,2,3]; Define an array
var newArr = []; To define a new temporary array
var result = {}; Hash table
for (Var i=0;i<arr.length;i++) {//Iterate through an array
if (!result[arr[i]]) {//If the traversed array is not in the hash table
Result[arr[i]] = true; Deposits the currently traversed array element into the hash table
Newarr.push (Arr[i]); Push the current element to a new array
}
}
Console.log (NEWARR);

The second method of
var arr=[23,1,34,7,1,3,5,2,3]; Define an array
var newArr = []; To define a new temporary array
for (Var i=0;i<arr.length;i++) {//traversal array
if (Newarr.indexof (Arr[i]) ==-1) Newarr.push (Arr[i]);
Determines whether the current element can be found in a temporary array, appends it to a temporary array if it is not found, and then continues to find and compare elements behind the current element
}

Console.log (NEWARR);

The Third Way
var arr=[23,1,34,7,1,3,5,2,3]; Define an array
Arr.sort (); Sort the array first
var newarr=[arr[0]]; Defines a new array and places the first element of the array in a new array
for (Var i=0;i<arr.length;i++) {
if (Arr[i]!==newarr[newarr.length-1]) {//By judging whether two adjacent items are equal, then appending elements to the new array, returning the new array
Newarr.push (Arr[i]);
}
}
Console.log (NEWARR);

</script>

Multiple methods for array de-weight implementation

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.