/    Sign up×
Community /Pin to ProfileBookmark

filter() behaviour

I have this array with repeating elements (length 15):
`let arr = [6, 8, 9, 9, 80, 80, 87, 88, 88, 88, 89, 89, 90, 91, 932]`
I want to remove all the duplicates, so wrote the following code:

“`
arr.filter((elem, index, arr) => {
if (arr[index] == arr[index+1]) {
arr.splice(index, 1)
}
})
“`

After logging arr, I got:

“`
[
6, 8, 9, 80, 87,
88, 88, 89, 90, 91,
932
]
“`

I can’t understand why I get 88 twice. This behaviour happens if an item is repeated more than twice. Any explanations/hints?

to post a comment
JavaScript

3 Comments(s)

Copy linkTweet thisAlerts:
@SempervivumMay 27.2020 — It's always tricky and error prone to manipulate the array itself when using filter or map. Instead I recommend to create a new one like this:
let arr = [6, 8, 9, 9, 80, 80, 87, 88, 88, 88, 89, 89, 90, 91, 932]
filteredArr = arr.filter((elem, index, arr) => {
return elem != arr[index + 1];
});
Copy linkTweet thisAlerts:
@KeverMay 27.2020 — It happens because you're modifying the array while filtering, you should just return true or false whether you want to keep the element or not.
arr.filter((elem, index, arr) => {
return arr[index] == arr[index+1];
});
Copy linkTweet thisAlerts:
@HawyauthorMay 27.2020 — @Sempervivum#1618840 Thank you a lot! It helped
×

Success!

Help @Hawy 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 4.25,
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: @Yussuf4331,
tipped: article
amount: 1000 SATS,

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

tipper: @Samric24,
tipped: article
amount: 1000 SATS,
)...