METHOD 1 - Using filter:
indexOf will return the first index (position) that a specific value first appear in the array. By checking indexOf(item)=== index, we can get the unique values.
let array = ["π", "π", "π", "π", "π", "π"];
const filterArr = array.filter((item, index) => array.indexOf(item) === index);
console.log(filterArr); //[ 'π', 'π' ]
Instead of checking for duplicates using array.filter() method, we can make use of the Set Data Structure that by definition only allows unique values.
METHOD 2 - Using Set:
const unique = (arr) => {
const nameSet = new Set();
for (let i = 0; i < arr.length; i++) {
nameSet.add(arr[i]); //add element to Set
}
Array.from(nameSet)
};
console.log(unique(values)); //[ 'π', 'π' ]
Shorter Method
const unique = (arr) => {
return Array.from(new Set(arr));
}
Set with Array Destructuring
const unique = (arr) => {
return [...new Set(arr];
}
METHOD 3 - Using Reduce:
const uniqueVal = array.reduce((unique, item) =>
unique.includes(item) ? unique : [...unique, item]
);
console.log(uniqueVal); //[ 'π', 'π' ]
Top comments (0)