How to remove duplicates from an array in JavaScript? The most efficient ways
Hello everyone! I'm a beginner in JavaScript and I've encountered a task: I have an array with numbers that has many duplicate values. I need to keep only unique elements. For example, I have an array `[1, 2, 2, 3, 4, 4, 5]`, and I want to get `[1, 2, 3, 4, 5]` as output.
I tried writing my own function, but it doesn't work correctly — it either doesn't remove all duplicates or breaks the array entirely. Here's my code:
```javascript
function removeDuplicates(arr) {
for (let i = 0; i < arr.length; i++) {
for (let j = i + 1; j < arr.length; j++) {
if (arr[i] === arr[j]) {
arr.splice(j, 1);
}
}
}
return arr;
}
```
The problem is that after `splice`, the indices shift, and I skip some elements. Plus, I think this is