how to get every unique element in an array? in typescript

To get every unique element in an array, you can use a combination of filtering and sets. Here's an example TypeScript code snippet:

const arr = [1, 2, 3, 3, 4, 4, 5];
const uniqueArr = [ Set(arr)]; // using the spread operator

console.log(uniqueArr); // [1, 2, 3, 4, 5]
145 chars
5 lines

In the above code, we first create an array arr with some duplicate elements. Then, we use the Set constructor to create a new set of only the unique values in arr. Finally, we convert the set back to an array using the spread operator ... and assign it to uniqueArr.

Now, uniqueArr contains only the unique elements of arr. We can verify this by logging uniqueArr to the console.

gistlibby LogSnag