-1

I found this function in Javascript to give an array and get an array without duplicates. Can someone please explain me every line of code?

function removeDuplicate(array) 
{

  var i, len=array.length, out=[], obj={};

  for (i=0;i<len;i++) 
    {
    obj[array[i]]=0;
    }
  for (i in obj)
    {
    out.push(i);
    }
  return out;
}

Thank you!

newtphp
  • 245
  • 1
  • 4
  • 13
  • Possible duplicate post .. http://stackoverflow.com/questions/840781/easiest-way-to-find-duplicate-values-in-a-javascript-array – thiago.lenz Jan 15 '14 at 18:53

1 Answers1

1

First are the variable definitions. 'i' is a idnex to the loop, and is later used as a value holder. 'len' is just shorthand for array.length. 'out' is a new array that is built as the function processes. Finally, 'obj' is an object where we store the values as we get them.

Now, we have the first loop, which iterates over the input array. Inside that loop, we create a property in obj using the array's values as property names and '0' as the property value. If any elements of the array have duplicate values, the same property name in 'obj' will be used ( this is where the duplicates are removed ).

Next Loop, we have a for loop on the properties in 'obj', and pushing those property names onto the 'out' array.

And the last line returns our 'out' array.

  • Thanks. So if array is [a,b,c,d,a] the object created in the first for is {a:0,b:0,c:0,d:0,a:0} but the property already exist so isn't added (i wrote it but it shouldn't be written). Does the value of the property 0 means no duplicates? Or we could have written anything instead of 0? – newtphp Jan 15 '14 at 19:08
  • Exactly right. The 0 is arbitrary, so any non-null value could be used. It's the fact that a property with that name already exists that causes it to work. – anthony barnhart Jan 15 '14 at 21:08