How do I make an array with unique elements (remove duplicates) - JavaScript?



Let’s say the following is our array with duplicate elements −

var duplicateNumbers = [10, 20, 100, 40, 20, 10, 100, 1000];

We want the output to be −

[10, 20, 100, 40, 1000];

To display only the unique elements, use the concept of filter.

Example

Following is the code −

var duplicateNumbers = [10, 20, 100, 40, 20, 10, 100, 1000]; console.log("With Duplicates Values="); console.log(duplicateNumbers); var noDuplicateNumbersArray = duplicateNumbers.filter(function (value, index, array) {     return array.indexOf(value) === index; } ); console.log("Without Duplicates Values=") console.log(noDuplicateNumbersArray);

To run the above program, you need to use the following command −

node fileName.js.

Here, my file name is demo234.js.

Output

The output is as follows −

PS C:\Users\Amit\JavaScript-code> node demo234.js With Duplicates Values= [     10,   20, 100,     40,   20,  10,    100, 1000 ] Without Duplicates Values= [ 10, 20, 100, 40, 1000 ]
Updated on: 2020-10-03T15:07:15+05:30

219 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements