/    Sign up×
Community /Pin to ProfileBookmark

Remove duplicate array elements

After sorting an array, is this the best way to [B]Remove duplicate array elements?[/B]

[code=html]<SCRIPT type=”text/javascript”>
var a=[‘a’,’a’,’b’,’c’,’c’,’d’,’d’,’d’,’t’,’y’,’y’,’j’,’j’]
document.write(a+’ <B>’+a.length+'</b><p>’)
i=0;while(i<a.length){if(a[i]==a[i+1]){a.splice(i,1);i–} i++}
document.write(a+’ <B>’+a.length+'</b>’)
</SCRIPT>[/code]

to post a comment
JavaScript

2 Comments(s)

Copy linkTweet thisAlerts:
@rnd_meMar 24.2010 — i don't know about "best", but i use [].filter() and [].lastIndexOf() to run the loop portion in C/JAVA:

[CODE]var a=['a','a','b','c','c','d','d','d','t','y','y','j','j'];
var b=a.filter(function(a,b,c){return c.lastIndexOf(a)===b;});[/CODE]


which yields:
[CODE]["a", "b", "c", "d", "t", "y", "j"][/CODE]


if you have a lot of strings and a lot of repetition, it can be faster (performance-wise) to use an object:

[CODE]var a=['a','a','b','c','c','d','d','d','t','y','y','j','j'];
var ok={}, b=[];
for(var i=0, mx=a.length,o; i<mx; i++){ ok[a[i]]=1; }
for(var i in ok){ b[b.length]=i; }
alert(b);
[/CODE]


this pattern avoids the loop-de-loop of your posted and my first method, but it doesn't work on objects.

that's not deal-breaker because your posted code has the same limitation.

the issue is that ["1", 1] will come out as a single-element array.
Copy linkTweet thisAlerts:
@mrhooMar 24.2010 — // Your method may do for a one off call,

// but you have to sort the array first,

// and you destroy the original array.

// Sometimes you want to preserve the order

// and return a unique array without losing the original


[CODE]Array.prototype.unique= function(){
var L= this.length, i= 0, a= [], tem;
while(i < L){
tem= this[i++];
if(tem!=undefined && a.indexOf(tem)== -1) a[a.length]= tem;
}
return a;
}[/CODE]


// Most browsers have an array indexOf method,

// but you need to add it for IE:

[CODE]Array.prototype.indexOf= [].indexOf ||
function(what, index){
index= index || 0;
var L= this.length;
while(index< L){
if(this[index]=== what) return index;
++index;
}
return -1;
}[/CODE]
×

Success!

Help @justinbarneskin spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.19,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,

tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,
)...