Find unique value from an array JavaScript

Опубликовано: 04 Август 2026
на канале: Erkon
142
3

To find a unique array and remove all the duplicates from the array in JavaScript,

First we use filter method and indexOf for finding unique value.

After ES6 we use the new Set() constructor and pass the array that will return the array with unique values.

https://developer.mozilla.org/en-US/d...

Raw code:

1st

1.//Create an array
2. const array = [1,2,2,3,4,4,4,5,5,6,7,7,7,8,8,1,2,2,3,4,4,4,5,5]
3.//Here we find uniqe array value usign filter method
4. const uniqueNum = array.filter(
5.// filter method gives 3 paramitter and we use it in our function
6. function(currE,index,arr){
7.// The indexOf() method returns the first index at which a given element can be found in the array, or -1 if it is not present.
8. return arr.indexOf(currE) === index;
9. })
10. console.log(uniqueNum);

2nd

1.//Create an array
2. const array = [1,2,2,3,4,4,4,5,5,6,7,7,7,8,8,1,2,2,3,4,4,4,5,5]
3.//Here we find uniqe array value usign Set() constructor
4. const uniqueNum = new Set(array)
5.// The Set constructor lets you create Set objects that store 7.//unique values of any type,
8. console.log(uniqueNum);