DEV Community

Cover image for πŸš€ Quick tips! 3 ways to get unique values from an array. πŸ’œ
Niall Maher
Niall Maher

Posted on

πŸš€ Quick tips! 3 ways to get unique values from an array. πŸ’œ

In this super short article, learn how to create 3 different functions that return all of the unique values in an array.

You can watch the video version here or keep scrolling for the code snippets.

1) Filter the values πŸ‘‡

const getUniqueValues = array => (
  array.filter((currentValue, index, arr) => arr.indexOf(currentValue) === index)
);
Enter fullscreen mode Exit fullscreen mode

2) Using reduce πŸ‘‡

const getUniqueValues = array => array.reduce(
  (accumulator, currentValue) => (
    accumulator.includes(currentValue) ? accumulator : [...accumulator, currentValue]
  ), []
);
Enter fullscreen mode Exit fullscreen mode

3) Destructure a new Set πŸ‘‡

const getUniqueValues = array => [...new Set(array)];
Enter fullscreen mode Exit fullscreen mode

Follow me on Twitter

Subscribe on CodΓΊ Community

Top comments (5)

Collapse
 
crs1138 profile image
Honza

It seems that the [... new Set(arr)] is way faster than the other two.

jsbench.me/xnkapa5nxq/1

Collapse
 
patarapolw profile image
Pacharapol Withayasakpunt • Edited

Set also reliably keep what is .add() first as well. But I never really tested [...new Set(arr)] on whether the sequence is kept.

Collapse
 
nialljoemaher profile image
Niall Maher

That's actually great to know too. Finally, my laziness is paying off. πŸ˜‚

Collapse
 
crs1138 profile image
Honza

HA! Exactly my thought on this topic πŸ˜‚

Collapse
 
dailydevtips1 profile image
Chris Bongers

Set is such a impressive and easy way to do this, love to use it <3