Skip to main content

Remove duplicates from an array (JavaScript)

In this post, we will see how to remove duplicates from an array in JavaScript.

We will look into two methods - ES6 and Vanilla JavaScript.

ES6 Method

In ES6, this is very simple using the Set constructor and the Spread syntax as below -
let array = [1, 3, 4, 1, 2, 4, 3, 4, 5, 7, 6, 5, 8];
let unique = [...new Set(array)];
console.log(unique);
The output of this code will be -
[ 1, 3, 4, 2, 5, 7, 6, 8 ]
Set - lets you store unique values of any type, whether primitive values or object references.
Spread - allows an iterable to be expanded in places where zero or more arguments (for function calls) or elements (for array literals) are expected, or an object expression to be expanded in places where zero or more key-value pairs (for object literals) are expected.

Using Vanilla JavaScript

If you want to use vanilla JavaScript, you can utilize Array.indexOf() and Array.filter() methods as follows -
var sandwiches = [
 "turkey",
 "ham",
 "turkey",
 "tuna",
 "pb&j",
 "ham",
 "turkey",
 "tuna"
];
var uniqueSandwiches = sandwiches.filter(function(sandwich, index) {
 return sandwiches.indexOf(sandwich) === index;
});
console.log(uniqueSandwiches);
The output of this code snippet will be -
[ 'turkey', 'ham', 'tuna', 'pb&j' ]
But how does this work? For example, “turkey” shows up at 0, 2, and 6 index. The line
sandwiches.indexOf(sandwich)
returns the first matching index of “turkey” always, hence when the index of “turkey” is 0, it is returned but for indexes 2 and 6, the condition becomes false and hence they are ignored. This is true for all the other duplicates.

Conclusion

In this post, we discussed two approaches of removing duplicates from an array in JavaScript - ES6 and Vanilla JS.

I would love to hear your thoughts on this post and would like to have suggestions from you to make this post better. 

Feel free to befriend me on Facebook, Twitter or Linked In or say Hi by email.

Happy Learning 😊

Comments

Popular posts from this blog

Parsing XML using Retrofit

Developing our own type-safe HTTP library to interface with a REST API can be a real pain as we have to handle many aspects - making connections caching retrying failed requests threading response parsing error handling, and more.  Retrofit, on the other hand, is a well-planned, documented and tested library that will save you a lot of precious time and headaches. In this tutorial, we are going to discuss how we can parse the XML response returned from  https://timesofindia.indiatimes.com/rssfeedstopstories.cms  using the Retrofit library. To work with Retrofit, we need three classes -  Model class to map the JSON data Interfaces which defines the possible HTTP operations Retrofit.Builder class - Instance which uses the interface and the Builder API which allows defining the URL endpoint for the HTTP operation. Every method of the above interface represents on possible API call. The request type is specified by using appropriate annotations (GET, POST). The respon

Threads in Java - CountDownLatch (Part 12)

A CountDownLatch is a synchronizer which allows one thread to wait for one or more threads before starts processing. A good application of  CountDownLatch is in Java server-side applications where a thread cannot start execution before all the required services are started. Working A  CountDownLatch is initialized with a given count which is the number of threads it should wait for. This count is decremented by calling countDown() method by the threads once they are finished execution. As soon as the count reaches to zero, the waiting task starts running. Code Example Let us say we require three services, LoginService, DatabaseService and CloudService to be started and ready before the application can start handling requests. Output Cloud Service is up! Login Service is up! Database Service is up! All services are up. Now the waiting thread can start execution. Here, we can see that the main thread is waiting for all the three services to start before starting its own

Threads in Java - yield(), sleep() and join() (Part 4)

Let's say we want to stop the execution of a thread. How do we do this? There are three methods in the Thread class which can be used to stop the execution of a thread. Let us discuss these methods one by one 1. Yield method Suppose there are two threads A and B. A takes 10 minutes to complete a job while B takes only 10 seconds. At first, A and B both are in the RUNNABLE state then Thread Scheduler gives resources to A to run. Now B has to wait for 10 minutes to do a 10 seconds job. This very inefficient. Wouldn't it be great if we have some way to prevent the execution of A in between so that B can run? Fortunately, yield() method helps us in achieving this.  If a thread calls yield() method, it suggests the Thread Scheduler that it is ready to pause its execution. But it depends upon the Thread Scheduler to consider this suggestion. It can entirely ignore it. If a thread calls yield() method, the Thread Scheduler checks if there is any thread with same/high