Nate
Nate

Reputation: 161

Removing duplicated element from array (utilizing Object) - Javascript

function removeDuplicate(num){
  var out=[];
  var obj={};

  for (x = 0; x < num.length; x++){
    obj[num[x]]=0;
  }
  for (x in obj){
    out.push(x);
  }
  return out;
}
var theNum = [1,1,2,3,3,3,4,4,5,6,7,7,7];
result = removeDuplicate(theNum);

alert(theNum);
alert(result);

hi everyone, I'm new to programming and I can't figure out how this solution works, it sounds to me like it's assigning Zero's into that object for every elements in that array...?

and for each x in object, insert them into array?... what values the X's carry at that point?

thank you so much for any helps

Upvotes: 0

Views: 60

Answers (4)

Zee
Zee

Reputation: 8488

Here you actually need to understand this part:

for (x = 0; x < num.length; x++){
  obj[num[x]]=0;
}

num[x] will have repeated values so everytime a duplicate value comes up it overwrites the same value again. For example:

In 1st iteration:

obj[num[x]] = obj[num[0]] = obj[1] = 0;

In 2nd iteration:

obj[num[x]] = obj[num[1]] = obj[1] = 0; //Since num[1] is again 1;

and so on.

So in both the above iteration you are overwriting the same value. hence the for loop results in :

obj = {
       1 : 0,
       2 : 0,
       3 : 0,
       4 : 0,
       5 : 0,
       6 : 0,
       7 : 0
      }

Then in the next for loop you simply extract the keys(1,2,..) and return it:

for (x in obj){
  out.push(x);//Push all the keys 1,2,3...
}

return [1,2,3...]//out

Upvotes: 0

jignesh
jignesh

Reputation: 1669

var theNum = [1,1,2,3,3,3,4,4,5,6,7,7,7];
var uniqueNum = [];
function removeDuplicate()
{
$.each(theNum, function(i, el){
    if($.inArray(el, uniqueNum) === -1) uniqueNum.push(el);
});

alert(theNum);
alert(uniqueNum);
}

Upvotes: 0

tning
tning

Reputation: 1251

Basically, this works like a hash set.

This for loop map each element in the array to 0.

for (x = 0; x < num.length; x++){
    obj[num[x]]=0;
}

// result obj
obj = {1 : 0,
       2 : 0,
       3 : 0,
       4 : 0,
       5 : 0,
       6 : 0,
       7 : 0}

This for loop copy all keys in the obj back to array.

for (x in obj){
    out.push(x);
}

// result array
out = [1, 2, 3, 4, 5, 6, 7]

Hope it can help you.

Upvotes: 1

epascarello
epascarello

Reputation: 207501

It can add what ever as the value. It could be a 1 or 100 or any string, object, etc.

All the code is doing is iterating over the array. It takes the value and uses it as a key for an object. The key is used to add a value to the object. If the key is duplicated, it just overrides it with the same value. Than the code just loops over the keys of the object to get the unique values.

Upvotes: 0

Related Questions