THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.
This tutorial explains different ways to remove duplicate elements from an array with code examples
Set(array)
, again convert to Array using Array(Set)
For example, the Input array contains the following elements
array=[1,11,1,2,3,1,3]
1 and 3 are repeated and removed from an array, the following is an array. Output:
array=[1,11,2,3]
There are multiple ways we can remove duplicate elements.
Set
is a data structure used to store unique elements.Here are the following steps required
array
into Set
using the constructorset
to Array
using the array constructorHere is an example
var numbers=[1,11,1,2,3,1,3]
let uniqueUnordered = Array(Set(numbers))
puts (uniqueUnordered)
Output:
[1,11,2,3]
Arrays contain order items, with this approach, Set does not follow the order
var numbers=[1,11,1,2,3,1,3]
var result = Set<Int>()
for i in numbers {
result.insert(i)
}
print(result)
🧮 Tags
Recent posts
Julia examples - Variable Type Nim example - Convert String to/from the Int How to get length of an array and sequence in Nim? Nim environment variables - read, set, delete, exists, and iterate examples? How to convert from single character to/from string in Nim?Related posts