JavaScript Remove Duplicates From Array

To remove duplicates from array JavaScript; Through this tutorial, i am going to show you how to remove duplicates from an array in javaScript.

Remove Duplicates From Arrays In JavaScript

There are 3 ways or methods to remove the duplicates from an array in JavaScript; as shown below:

  • To remove duplicates from array in javascript using Set Object
  • To remove duplicates from array javascript using Array.filter() Method
  • To remove duplicates from array javascript using foreach loop

To remove duplicates from array in javascript using Set Object

Using the javaScript set object method, you can remove duplicate from an array.

Let, you have a numeric array and it contains duplicate elements and you can remove the duplicate elements from array. So you see the example given below

    var number = [1, 2, 1, 3, 4, 5, 2, 6, 3, 4];
    var unique = [...new Set(number)];
  
    document.write( "Output :- " + unique ); 

Result of the above code is: Output :- 1,2,3,4,5,6

To remove duplicates from array javascript using Array.filter() Method

Using javaScript array filter() and indexof() method, you can remove duplicates elements or values from array in javaScript.

As you have seen in the above example, how to remove duplicate elements from array using new set() method in JavaScript. In this example how to remove duplicate object and element from array using filter() and indexof() method in JavaScript; as shown below:

    var number = [1, 2, 1, 3, 4, 5, 2, 6, 3, 4];
    
    var x = (number) => number.filter((v,i) => number.indexOf(v) === i)
  
    document.write( "Output :- " + x(number) ); 

Result of the above code is: Output :- 1,2,3,4,5,6

To remove duplicates from array javascript using foreach loop

Using the javaScript array.forEach method, you can easily remove duplicates values or elements from array.

You can see the example of remove duplicates from array javascript using forEach:

    var number = [1, 2, 1, 3, 4, 5, 2, 6, 3, 4];
	function removeDuplicateFromArray(number) {
	  var uniqueVal = {};
	  number.forEach(function(i) {
	    if(!uniqueVal[i]) {
	      uniqueVal[i] = true;
	    }
	  });
	  return Object.keys(uniqueVal);
	}
  
    document.write( "Output :- " + removeDuplicateFromArray(number) ); 

Result of the above code is: Output :- 1,2,3,4,5,6

More JavaScript Tutorials

Recommended:-JavaScript Arrays

Be First to Comment

Leave a Reply

Your email address will not be published.