Remove Duplicates From Array JavaScript

How To Remove Duplicates From Array JavaScript? – Steps To Follow

Tech & Innovation 28 November 2023 6 Mins Read

How can you remove duplicates from array JavaScript? – There are various ways you can do so. In a JavaScript array, you can store numerous elements or a group of values within a single variable. With the help of various functions, you will be able to remove duplicate elements from the JavaScript array.

In this article, you will learn how to remove duplicate elements from an array in JavaScript. We will use six different ways where we will use six different methods to remove duplicate elements in a program. However, before that, we will have some basic idea of how a JavaScript array works. Hence, to learn more, read on through to the end of the article.

What Is JavaScript?

What Is JavaScript

According to GeeksForGeeks.org,

JavaScript is a lightweight, cross-platform, single-threaded, and interpreted compiled programming language. It is also known as the scripting language for web pages. It is well-known for the development of web pages, and many non-browser environments also use it.

Coders use JavaScript for client-side developments and server-side developments. It contains various library objects, as well as language elements.

What Is A JavaScript Array?

What Is A JavaScript Array

According to DigitalOcean.com,

An array in JavaScript is a type of global object that is used to store data. Arrays consist of an ordered collection or list containing zero or more data types and use numbered indices starting from 0 to access specific items. Arrays are very useful as they store multiple values in a single variable, which can condense and organize our code, making it more readable and maintainable.”

An array can contain all data types, which might include numbers, objects, and strings. You can create an array in two ways:

  • Array Literal: You can create it using square (third) brackets.
  • Array Constructor: You can create it using the ‘new’ keyword

The Best Ways To Remove Duplicates From Array JavaScript

Here are the methods you can use to remove duplicate elements from an array in JavaScript:

  1. Filter method
  2. Sets
  3. forEach method
  4. reduce method
  5. indexOf method
  6. Underscore JS

You have to use each of these methods in your JavaScript program to remove all duplicates from a single array. The following are the best ways with which you can remove duplicates from a JavaScript array program:

1. Using The ‘Filter’ Method

Once you use the filter() method, it will create a new array consisting of new elements. These elements help to pass the conditional that you provide. The element which fails to pass the conditional or returns a ‘false’, will not be filtered in the JavaScript array.Here is an example where you can use the filter() method:

Here is an example where you can use the filter() method:

let arr = [“cat”, “dog”, “cat”, “elephant”, “dog”, “dog”];
function removeDuplicates(arr)
{  
    
return arr.filter((item, index) => arr.indexOf(item) === index);

}

console.log(removeDuplicates(arr)); 


Output:[“cat”, “dog”, “elephant”]

2. Create Unique Values With The ‘Set’ Method

Sets create a new object type in the program. With the help of this object type, you can create collections of unique values.

Basically, a ‘Set’ consists of a collection of unique values. You have to convert the array of duplicates to a Set first. It will create a new Set. This new Set will eventually remove all duplicate elements from the array. You will need to then covert the Set back to an array to remove the duplicate values finally.

Here is an example of using the ‘Set()’ method in JavaScript:

let arr = [“cat”, “dog”, “cat”, “elephant”, “dog”, “dog”];
function removeDuplicates(arr)
{        
return […new Set(arr)];

}

console.log(removeDuplicates(arr));  

Output:[“cat”, “dog”, “elephant”]

3. Iterate Using forEach Method

With the help of the ‘forEach()’ method, you will be able to iterate the elements in the array. Thus, you can push it into the new array if the array does not consist of the element.

let arr = [“cat”, “dog”, “cat”, “elephant”, “dog”, “dog”];
function removeDuplicates(arr)
{          
let unique = [];          
arr.forEach(element =>
{      
if (!unique.includes(element))
{            
unique.push(element);
}
});            
return unique;
}
console.log(removeDuplicates(arr));  

Output:[“cat”, “dog”, “elephant”]

4. Use The ‘Reduce’ Method

You can use the reduce method in JavaScript to reduce the array elements. It helps you combine the elements in the final array based on the reducer function you pass.

Here is an example of the reduce() method in JavaScript:

let arr = [“cat”, “dog”, “cat”, “elephant”, “dog”, “dog”];
function removeDuplicates(arr)
{        
let unique = arr.reduce(function (acc, curr);
{            
if (!acc.includes(curr))            
acc.push(curr);            
return acc;   
}, []);

return unique;
}

console.log(removeDuplicates(arr)); 

Output:[“cat”, “dog”, “elephant”]

5. Add The IndexOf Method

With the help of the indexOf() method, you will be able to find the first index of occurrence of an array element. You can use it to iterate over the elements in the array. Furthermore, you can push the element into the new array if the element does not exist in the resultant array.

Here is an example of removing duplicates with the indexOf method in JavaScript:

let arr = [“cat”, “dog”, “cat”, “elephant”, “dog”, “dog”];

function removeDuplicates(arr)
{         
let unique = [];         
for (i = 0; i < arr.length; i++)
{         
if (unique.indexOf(arr[i]) === -1)
{            
unique.push(arr[i]);
}
}             
return unique;
}
console.log(removeDuplicates(arr)); 

Output:[‘cat’, ‘dog’, ‘elephant’]

6. Use Underscore ‘Uniq’

By using the ‘_.uniq’ method, you can produce a duplicate-free version of the array. You can also sort this array when you pass the second parameter as true.

Here is how you can use the underscore “.uniq()” function in JavaScript:

<!DOCTYPE html>
<html> 

<head>    
<script src= “https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js”>    
</script>
</head>
<body>    
<script type=”text/javascript”>       
console.log(_.uniq([1, 2, 3, 4, 5, 4, 3, 2, 1]));    
</script>
</body> 


</html>

Wrapping Up

Hope this article was helpful for you in understanding how to remove duplicates from array JavaScript. If you have accidentally used an element more than once in an array, you can use the functions mentioned above to remove them. Among all the methods that are present in this article, the ‘filter()’ and the ‘sets()’ methods are the simplest and most popular. Do you have any more information about these methods? Consider sharing these pieces of information with us in the comments section below.

Get High On Business With Our Articles!!

tags

coding javascript Array programming remove Duplicates web Development

A passionate writer and an avid reader, Soumava is academically inclined and loves writing on topics requiring deep research. Having years of content writing experience, Soumava also loves creating blogs in other domains, including digital marketing, business, technology, travel, and sports.

Leave a Reply

Your email address will not be published. Required fields are marked *

may you also read

network security key
Stripe
Everything You Need To Know About Byjus