Here are 3 ways to retrieve unique values from arrays in Javascript
The array.filter
method which is a higher order function which means it takes a function as it's argument.
const someArray = [ 'π' , 'π' , 'π' , 'π©' , 'π' , 'π' , 'π' ] ;
const getUniqueValues = ( array ) => (
array . filter ( ( currentValue , index , arr ) => (
arr . indexOf ( currentValue ) === index
) )
)
console . log ( getUniqueValues ( someArray ) )
// Result ["π", "π", "π©", "π"]
The array.reduce
method which is a higher order function which means it takes a function as it's argument.
const someArray = [ 'π' , 'π' , 'π' , 'π©' , 'π' , 'π' , 'π' ] ;
const getUniqueValues = ( array ) => (
array . reduce ( ( accumulator , currentValue ) => (
accumulator . includes ( currentValue ) ? accumulator : [ ...accumulator , currentValue ]
) , [ ] )
)
console . log ( getUniqueValues ( someArray ) )
// Result ["π", "π", "π©", "π"]
Using the Set
method.
const someArray = [ 'π' , 'π' , 'π' , 'π©' , 'π' , 'π' , 'π' ] ;
const getUniqueValues = ( array ) => (
[ ...new Set ( array ) ]
)
console . log ( getUniqueValues ( someArray ) )
// Result ["π", "π", "π©", "π"]