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