JS traversal array duplicate values and objects duplicate values in a group

Source: Internet
Author: User

Array to remove duplicate values:

The Arr.indexof () method returns the position of the first occurrence of a specified string value in the second character,  or 1 if none is present in the array.
var arr=[2,8,5,0,5,2,6,7,2];function unique1 (arr) {  var result=[];  for (var i = 0; i < arr.length; i++) {     if (Hash.indexof (Arr[i]) ==-1) {      resule.push (arr[i]);     }  }  return result;}

The repetition of object removal in the array is worth the method:
var arr=[
{ID: "45545", Text: "Admin"},
    {ID: "4556545", Text: "Preview"},
    {ID: "455455", Text: "No Permission"},
     {ID: "45545", Text: "Admin"}
];
Method 1
var result=[];
var obj={};
for (i=0;i<arr.length;i++)
{
if (!obj[arr[i].id])
{
Resule.push (Arr[i]);
Obj[arr (i). Id]=true;
}
}
Console.log (Result)

     Method 2: Use the Reduce method to iterate through the array, and reduce the first parameter to traverse the function that needs to be executed, the second parameter is the initial value of item       var obj = {};       arr = arr.Reduce(function (item, next) {           ? ": obj[next.key] = True && Item.push (next);       return item;    }, []);


      
A different way
arr = arr.Reduce(function (item, next) {;
if (!obj[next.key])
{
Item.push (next);
Obj[next.key]=true

} return item; }, []);


JS traversal array duplicate values and objects duplicate values in a group

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.