This content originally appeared on DEV Community and was authored by KenjiGoh
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); //[ '๐', '๐' ]
This content originally appeared on DEV Community and was authored by KenjiGoh
KenjiGoh | Sciencx (2022-02-10T10:04:00+00:00) Filter unique array members (remove duplicates). Retrieved from https://www.scien.cx/2022/02/10/filter-unique-array-members-remove-duplicates/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.