Removing duplicated element from array (utilizing Object) - Javascript -
function removeduplicate(num){ var out=[]; var obj={}; (x = 0; x < num.length; x++){ obj[num[x]]=0; } (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 programming , can't figure out how solution works, sounds me it's assigning zero's object every elements in array...?
and each x in object, insert them array?... values x's carry @ point?
thank helps
here need understand part:
for (x = 0; x < num.length; x++){ obj[num[x]]=0; }
num[x]
have repeated values everytime duplicate value comes overwrites same value again. 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] again 1;
and on.
so in both above iteration overwriting same value. hence loop results in :
obj = { 1 : 0, 2 : 0, 3 : 0, 4 : 0, 5 : 0, 6 : 0, 7 : 0 }
then in next loop extract keys
(1,2,..) , return it:
for (x in obj){ out.push(x);//push keys 1,2,3... } return [1,2,3...]//out
Comments
Post a Comment