how to use the unique function from the underscore library in typescript

To use the unique function from the Underscore library in TypeScript, you can first install the Underscore library using npm by running the command:

npm install underscore
23 chars
2 lines

Then, you can import the library and use the unique function as follows:

index.ts
import * as _ from 'underscore';

const myArray: number[] = [1, 2, 2, 3, 3, 3, 4, 5, 5];
const uniqueArray: number[] = _.unique(myArray);

console.log(uniqueArray); // Output: [1, 2, 3, 4, 5]
192 chars
7 lines

Here, we import the underscore library using the import statement and assign it to a variable named _. We then declare an array of numbers myArray which contains duplicate values. Finally, we use the unique function to create a new array uniqueArray which contains only the unique values from the myArray array.

Note: You can also use the uniq function instead of unique if you prefer the shorter name.

gistlibby LogSnag