- #javaScript
- #arrays
- #snippets
Introduction
The easiest way to remove duplicates from an array is using the Set() object but there are other possibilities. For example looping (or interating) an array and applying the includes() method on the array elements. Let’s tale a look.
For loop with .includes() method
const nums = [1,3,5,7,9,3,2,6,8,9,1,3,5,7]
const unique = []
for (let i = 0; i < nums.length; i++) {
if (!unique.includes(nums[i])) {
unique.push(nums[i])
}
}
// unique
// [1, 3, 5, 7, 9, 2, 6, 8]
The nums array contains a lot of numbers some of whch are repeated. A for loop is used to check if each array element is included in the unique array. If not, that number is pushed into the unique array.
It starts at the first element 1 at nums[0]. Is it included in the empty unique array? No. Then 1 is added to the end of the unique array using the .push() method. Then the second element 3 at nums[1]. Is it included in the empty unique array? No. Then 3 is added to the end of the unique array using the .push() method. And so on.
forEach loop with .includes() method
We can remove duplicates from an array using a forEach loop and include() and push() methods.
const names = ['David', 'Clare', 'Yasmin', 'David', 'clare']
const unique_names = []
names.forEach((name) => {
if (!unique_names.includes(name)) {
unique_names.push(name)
}
})
// ['David', 'Clare', 'Yasmin', 'clare']
Similar to the for loop, forEach iterates over each name, checks whether it is included in the unique_names array. If not the name is pushed into it.
Notice that this approach is case sensitive and both ‘Clare’ and ‘clare’ are in the unique_names array. To get around this problem, the .toLowerCase() method could be used on each name.
const names = ['David', 'Clare', 'Yasmin', 'David', 'clare']
const unique_names = []
names.forEach((name) => {
if (!unique_names.includes(name.toLowerCase())) {
unique_names.push(name.toLowerCase())
}
})
// ['david', 'clare', 'yasmin']
Summary
It is possible to remove duplicates from an array using a loop and a combination of methods. However, removing duplicate elements from array with Set() uses less code for the same task. See my post Remove duplicate elements from array with loops. for the detail.
That’s it.
Thank you for stumbling across this website and for reading my blog post entitled Remove duplicate elements from array with loops