Remove duplicates from an array in JavaScript
This post will discuss how to remove duplicate values from an array in JavaScript.
1. Using Array.filter() function
A simple solution is to check the second occurrence for each array element. This can be easily done using the indexOf() method with the filter() method in the following manner:
|
1 2 3 4 5 6 7 |
var arr = [ 1, 3, 5, 1, 2, 3, 7, 4, 5]; var unique = arr.filter((x, i) => arr.indexOf(x) === i); console.log(unique); /* Output: [ 1, 3, 5, 2, 7, 4 ] */ |
2. Using Set
The above solution is not recommended because of serious performance concerns for large arrays. An efficient solution is to convert the array into a Set data structure and then transform the set back into an array. This solution works as a Set store unique values and eliminates duplicate values. Note that this solution might change the original ordering of elements present in the array. This can be implemented using the Set constructor and Array.from() method.
|
1 2 3 4 5 6 7 |
var arr = [ 1, 3, 5, 1, 2, 3, 7, 4, 5]; var unique = Array.from(new Set(arr)); console.log(unique); /* Output: [ 1, 3, 5, 2, 7, 4 ] */ |
Alternatively, you can use the Spread operator (...) to convert the set back into an array.
|
1 2 3 4 5 6 7 |
var arr = [ 1, 3, 5, 1, 2, 3, 7, 4, 5]; var unique = [...new Set(arr)] console.log(unique); /* Output: [ 1, 3, 5, 2, 7, 4 ] */ |
3. Using Underscore/Lodash Library
In case you don’t want to use the Set data structure, Underscore, or Lodash JavaScript library provides the uniq() method, which returns a duplicate-free version of an array.
|
1 2 3 4 5 6 7 8 9 |
var _ = require('underscore'); var arr = [ 1, 3, 5, 1, 2, 3, 7, 4, 5]; var unique = _.uniq(arr); console.log(unique); /* Output: [ 1, 3, 5, 2, 7, 4 ] */ |
4. Using jQuery
If you’re using the jQuery library, consider using the grep() method, which works similarly to the JavaScript filter() method. The following example demonstrates its usage:
|
1 2 3 4 5 6 7 8 9 10 11 |
const { JSDOM } = require("jsdom"); const { window } = new JSDOM(); var $ = require("jquery")(window); var arr = [ 1, 3, 5, 1, 2, 3, 7, 4, 5]; var unique = $.grep(arr, (x, i) => $.inArray(x, arr) === i); console.log(unique); /* Output: [ 1, 3, 5, 2, 7, 4 ] */ |
5. Using Array.reduce() function
Finally, you can use the reduce() method in the following manner to remove duplicates from an array:
|
1 2 3 4 5 6 7 |
var arr = [ 1, 3, 5, 1, 2, 3, 7, 4, 5]; var unique = arr.reduce((prev, cur) => (prev.indexOf(cur) === -1) ? [...prev, cur] : prev, []); console.log(unique); /* Output: [ 1, 3, 5, 2, 7, 4 ] */ |
That’s all about removing duplicates from an array in JavaScript.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)